I have written an increbily simple event listener and yet it comes up with the error: Uncaught TypeError: Cannot call method 'addEventListener' of null
which suggests it is to do with the id maybe (also it works with document
?
<html>
<head>
<script type="text/javascript">
function message () {
alert("Hello!");
}
var button = document.getElementById('button');
button.addEventListener('click', message, true);
</script>
</head>
<body>
<input type="button" id="button" value="Click me!" />
</body>
</html>
(I know I'm going to feel stupid after this, but I am a JS noob)
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.
You can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements. i.e the window object.
Using the once option We can pass an object as an argument to the addEventListener method and specify that the event is only handled once. This is achieved by passing the property once to the object. If we set once to true, the event will only be fired once.
at the time your script executes, the DOM has not been created. you can place your script after the body tags to run it after reading the html - but the better way to do it is by listening for DOMContentLoaded
.
document.addEventListener('DOMContentLoaded', init, false);
function init(){
function message () {
alert("Hello!");
}
var button = document.getElementById('button');
button.addEventListener('click', message, true);
};
window.onload = init
works too. I don't like it because it looks to me like one script could overwrite window.onload to be its own init function. (i haven't confirmed that happens or not)
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