Monday, September 22, 2014

Javascript: addEventListener not working

Problem: Code below is not firing up the event handler function

<html>
<head>
    <script type="text/javascript">
        function fireEventButton()
        {
            document.getElementById("list").innerHTML = "hi hi World";
        }
        document.getElementById("myBtn").addEventListener("click", fireEventButton, false);        
    </script>
</head>
<body>
    <button id="fireEvent">Click to fire Event Handler</button>
    <p id = "output"></p>        
</body>
</html>


Cause:
It does not work because the DOM is not ready yet and is already being assigned the event handler function.

Solution:
wrap the event handler assignment in the onload() function of either the <body> or the window.

<html>
<head>
    <script type="text/javascript">
        function init()
        {
            document.getElementById("fireEvent").addEventListener("click", fireEventButton, false);
        }
   
        function fireEventButton()
        {
            document.getElementById("output").innerHTML = "event handler executed!";
        }
             
    </script>
</head>
<body onload="init()" >
    <button id="fireEvent">Click to fire Event Handler</button>
    <p id = "output"></p>      
</body>
</html>

Or you can do this:

<html>
<head>
    <script type="text/javascript">
        function init()
        {
            document.getElementById("fireEvent").addEventListener("click", fireEventButton, false);
        }
     
        window.addEventListener('load',function()
            {
                document.getElementById("fireEvent").addEventListener("click", fireEventButton, false);
            }
        );
   
        function fireEventButton()
        {
            document.getElementById("output").innerHTML = "event handler executed!";
        }
             
    </script>
</head>
<body onload="init()" >
    <button id="fireEvent">Click to fire Event Handler</button>
    <p id = "output"></p>      
</body>
</html>

No comments:

Post a Comment