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

177
Vistas
Why is my javascript event listener only working one time?

I'm still so new to JavaScript so bear with me. I am trying to get a dice roll to work in JavaScript when a button is clicked. I declared the roll function but when I recall it with a parameter the event listener only runs once when the page is loaded and that's it. Weirdly enough everything I find on google is from people specifically trying to get it to only run once. Thoughts?

document.querySelector('#roll').addEventListener('click', roll)


function roll(diceSides) {
console.log(Math.floor(Math.random() * diceSides) + 1)

}

roll(6)
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Your "event listener" is actually never firing in your example. You are simply calling your function at the end of the code roll(6). The reason you are not calling it in your event listener is because you are not giving your roll function a number of diceSides in your callback. (by default it gets the event object as the param)

There are two [easy] ways to solve this:

document.querySelector('#roll').addEventListener('click', ()=>roll1(6))


function roll1(diceSides) {
  console.log("roll1",Math.floor(Math.random() * diceSides) + 1)
}


function roll2(diceSides=6) {
  console.log("roll2",Math.floor(Math.random() * diceSides) + 1)
}
document.querySelector('#roll').addEventListener('click', ()=>roll2())
<button id="roll">Click me!</button>
You can either pass a function with the value in it (as seen in roll1 function) OR You can give a default (as seen in roll2 function)

Either way you MUST call the function in the callback. You can get around this by passing an arrow function as seen in both of the code examples.

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