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
If your event listener not working is dependent on some logic, whether it's about which element it'll listen on or if it's registered at all, the first step is to check that the listener is indeed added to the element. Using a breakpoint in the developer tools , a logpoint or console.
With the addEventListener() method you can specify the propagation type by using the "useCapture" parameter: addEventListener(event, function, useCapture); The default value is false, which will use the bubbling propagation, when the value is set to true, the event uses the capturing propagation.
Both can be used to handle events. However, addEventListener should be the preferred choice since it can do everything onclick does and more. Don't use inline onclick as HTML attributes as this mixes up the javascript and the HTML which is a bad practice. It makes the code less maintainable.
The error "Cannot read property addEventListener of null" occurs when we call the addEventListener() method on a DOM element that doesn't exist. To solve the error, use an if statement to check if the DOM element exists before calling the addEventListener() method. Copied! const btn = document.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With