0
Event Listener Error
So, I'm working on a code that uses event listeners. On the JavaScript, it has this line: var buttonUp = document.getElementById("up") buttonUp.addEventListener("click", moveUp) The "moveUp" function is declared later. Then, in the HTML: <button id="up">up</button> It gets an error saying "cannot read property "addEventListener" of null." It shouldn't be null as it's defined before adding the event listener. Why is the code producing this error?
1 ответ
+ 3
The problem probably is, that you declared the "buttonUp" variable before the page was loaded.
You should do it like this:
window.onload = () => {
buttonUp = document.getElementById("up");
buttonUp.addEventListener("click", moveup);