addEventListener doesn't work

Hi all.

I was trying to get some random color for a box just for some action. So I wrote down just a function and it worked for onclick event. But when I used eventlistener id didnt work at all. Is there any problem with codepen and addEventListener ?

Here is my pen!

Thank you!

document.getElementById("box").addEventListener("click", colorG());

When you use parentheses on a function, you invoke it. In this case, you’re telling the browser that each time #box is clicked on, execute the return value of colorG. You want it to run the colorG function itself.

document.getElementById("box").addEventListener("click", colorG); // <-- no parens
2 Likes