0

I have a javascript code written following the module pattern:

var controller = function () {

    return {
        init: function() {
            // settings and initialization    
        }

        makeUIactions: function() { 
             //set UI actions, for example callback function of a button:
            document.getElementById("ShuffleButton").addEventListener("click", Shuffle);
            function Shuffle(){};
        }
    }
}

How do I pass by document object to makeUIactions?

P/S: I got the following error:

Cannot read property 'addEventListener' of null

Is it because I can't access document from makeUIactions?

HTML:

<script>
    controller.init();
    controller.makeUIactions();
</script>

<div>
    <input type="button" id="ShuffleButton" style="margin-top:20px" value="Shuffle" data-inline="true">

    <input type="button" id="SubmitButton" style="margin-top:20px" value="Submit" data-inline="true">
</div>
Dzung Nguyen
  • 3,240
  • 8
  • 33
  • 75

1 Answers1

2

Your code is running BEFORE the DOM has been loaded thus, document.getElementById("ShuffleButton") cannot find the DOM element so it returns null. When you then try null.addEventListener(), it throws the error you see.

You can fix it by moving this:

<script>
    controller.init();
    controller.makeUIactions();
</script>

to be right before your </body> tag so that the DOM elements are in place before the script runs. See this answer pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it for lots more details.

Community
  • 1
  • 1
jfriend00
  • 580,699
  • 78
  • 809
  • 825