Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
Initializing JavaScript class before using it later in an html file

I have the following problem. I developed a javaScript class that is being used in conjunction with a select tag. Since the javaScript class has to parse through the DOM of the page, I would rather initialize the class once the DOM finishes loading and not necessarily when the user chooses a value from the select element. I was wondering what would be the best practice to do this.

I currently have the following code in the head:

<script>
    window.addEventListener('DOMContentLoaded', (event) => {
  
      // As soon as DOM content is loaded initialize class and have class parse through DOM     
      obj = new Object();
      
    });
</script>

and the following select down in the body:

<select name="select" id="select" onChange="obj.function(this);">
    <option value="value1">Value1</option>
    <option value="value2">Value2</option>
</select>   

However, when I run this I get an uncaught reference error for obj. What would be the best practice for this?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You should bind select event onChange after that document is ready to use new instance.

<script>
    window.addEventListener('DOMContentLoaded', (event) => {
  
      // As soon as DOM content is loaded initialize class and have class parse through DOM     
      obj = new Object();
      sel = document.getElementById('select')
      sel.onChange = obj.function(sel)
    });
</script>

...

<select name="select" id="select">
    <option value="value1">Value1</option>
    <option value="value2">Value2</option>
</select>   

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!