AddEventListener not working in javascript

I am studying addEventListener, I tested one of the examples, but did not work. Can someone tell me what I'm 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

+7
source share
3 answers

Your elements were not found because you are running javascript before adding elements. Try moving the script to the lower 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> 
+11
source

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

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

Your code does not work because the DOM is not ready yet and you are already trying to extract id1 and id2.

+7
source

Your code throws below an error in the console: Uncaught TypeError: It is not possible to call the 'addEventListener' method from null which indicates that you need to first define your html element (anchor in this case) and then call methods on it.

What you do is the first call method (addEventListener in this case) and the html element definition (anchor in this case) later.

  <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> 
+1
source

All Articles