Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

120
Vistas
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?
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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);
});
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda