Event Listener Error | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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?

18th May 2019, 8:32 PM
Pokémaniac7
Pokémaniac7 - avatar
1 Answer
+ 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);
18th May 2019, 9:01 PM
Airree
Airree - avatar