addEventListener not working in javascript

I am learning addEventListener,I was testing one of the example but its not working .Can anybody tell me what i am doing wrong

<html>
<head>
<script type="text/javascript">
function click_handler1() { alert("click_handler1"); }
function click_handler2() { alert("click_handler2"); }

    document.getElementById("id1").addEventListener("click", click_handler1, false);
    document.getElementById("id2").addEventListener("click", click_handler2, false);

//window.addEventListener("load", setup, false);
</script>
</head>
<body>
<a id="id1">some stuff</a>
<a id="id2">stuff</a>
</body>
</html>

Thanks

Answers:

Answer

Your elements are not found because you're executing the javascript before you've added the elements. Try moving the script to the bottom of the body:

<html>
<head>
</head>
<body>
<a id="id1">some stuff</a>
<a id="id2">stuff</a>
<script type="text/javascript">
function click_handler1() { alert("click_handler1"); }
function click_handler2() { alert("click_handler2"); }

    document.getElementById("id1").addEventListener("click", click_handler1, false);
    document.getElementById("id2").addEventListener("click", click_handler2, false);

//window.addEventListener("load", setup, false);
</script>
</body>
</html>
Answer

Move this to the end of the document, or wrap it with an onload function:

window.addEventListener('load',function(){
    document.getElementById("id1").addEventListener("click", click_handler1, false);
    document.getElementById("id2").addEventListener("click", click_handler2, false);
});

Your code doesn't work because the DOM is not ready yet and you are already trying to fetch id1 and id2.

Answer

Your code throws below error in console: Uncaught TypeError: Cannot call method 'addEventListener' of null which specifies you need to first define your html element (anchor in this case) and then call methods on it.

What you are doing is - first calling method (addEventListener in this case) and defining the html element (anchor in this case) later on.

    <html>
    <head></head>
    <body>
    <a id="id1">some crap</a><br>
    <a id="id2">crap</a>
    <script type="text/javascript">
     function click_handler1() { alert("click_handler1"); }
     function click_handler2() { alert("click_handler2"); }

     document.getElementById("id1").addEventListener("click", click_handler1);
     document.getElementById("id2").addEventListener("click", click_handler2);
    </script>
    </body>
    </html>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.