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?

5/18/2019 8:32:15 PM


1 Answer

New Answer


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);