Skip to content
Advertisement

addEventListener to all buttons using forEach

I am trying to addEventListener to all of my buttons. This is my first time using addEventListener and it is not running the usergetNumber function which should display a random number when any button is clicked.

const btns = document.querySelectorAll(".button");

btns.forEach(function(i) {
    i.addEventListener('click', usergetNumber(){
    });

function usergetNumber(){
    const userRanNum = Math.floor(Math.random() * 10)
    userscore_div.innerHTML = "You have " + userRanNum + " points";
    computergetNumber();

function computergetNumber(){
    const compRanNum = Math.floor(Math.random() * 10)
    computerscore_div.innerHTML = "You have " + compRanNum + " points";
}

What am I doing wrong?

Advertisement

Answer

From top to bottom.

  1. There’s already a function usergetNumber() { ... } declaration in addEventListener(). It’s a function declaration not a callback here. Ref: Event Listener Callbacks.
  2. The closing bracket on usergetNumber() { ... is missing so therefore it isn’t declared.

Here’s a basic example. You can also just return and not console.log. Here, I’m just trying to duplicate the logic.

const btn = document.querySelectorAll('button');
    
function getRandomNum() {
  let randomNum = Math.random();
  console.log(randomNum);
} 

btn.forEach(function(button) {
  button.addEventListener('click', getRandomNum);
});
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement