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>
5
  • How do I pass by document object to makeUIactions? Explain this a little more. What are you trying to do? Commented Mar 9, 2015 at 5:11
  • 3
    The document object is a global variable in a browser accessible from anywhere. It does not need to be passed unless you're using some sort of embedded document like an iframe. Commented Mar 9, 2015 at 5:12
  • Why you want to pass that.. Commented Mar 9, 2015 at 5:13
  • 1
    Can you show us the HTML? Seems there is no element with the ID of ’button'. Commented Mar 9, 2015 at 5:21
  • 1
    Try to load script at the end..or you can specify your functionalities inside window.onload.. Commented Mar 9, 2015 at 5:30

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.