Sublime Forum

Novice JavaScript working in CodePen, not in ST3

#1

Can anyone give some ideas about why the following js code is working in codepen, but giving me an error in the chrome console that indicates the button variable is null?

“Uncaught TypeError: Cannot read property ‘addEventListener’ of null…”

The script is…
`var button = document.getElementById(‘button’);
var rainbow = [“red”, “orange”, “yellow”];

function change() {
document.body.style.background = rainbow[Math.floor(3*Math.random())];
}
button.addEventListener(“click”, change);`

In the chrome console, button is ‘null’, but rainbow shows the array just fine.

Thank you!

0 Likes

#2

Hello everyone. I found the solution.
My link to the script file needed to be at the bottom of the html file.
:blush:

I’m not seeing how to mark this as resolved…

0 Likes