Search code examples
javascripthtmlweb-deployment

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?


Solution

  • 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>