Add event listener failing

let generateButton = document.querySelector('.cta')
let colorBox = document.querySelector('.color-box')

const generateNumber = () => {
  return Math.floor(Math.random() * 256)
}


colorBox.style.backgroundColor = "lightblue";

generateButton.addEventListener('click', generateNumber)

when i press the button associated with generate button, it does not generate number? why is this so? what is wrong?

Hello!

I don’t know what you’re trying to do after you generate the number, but you can be sure it’s generating it.

Change your code to this:

let generateButton = document.querySelector('.cta')
let colorBox = document.querySelector('.color-box')
let generatedNumber = null;

const generateNumber = () => {
  generatedNumber = Math.floor(Math.random() * 256)
  alert("Generated number: " + generatedNumber);
}

colorBox.style.backgroundColor = "lightblue";
generateButton.addEventListener('click', generateNumber)
1 Like

Take a look at this link on devdocs, and pay particular attention to what addEventListener actually returns.

https://devdocs.io/dom/eventtarget/addeventlistener

2 Likes

What that means is, even if your callback function returns something? addEventListener doesn’t catch your functions returned value - because addEventListener returns undefined.

2 Likes

Thank you! I realized I did something and got a value, but did nothing with the value. Gotta be more careful

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.