Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

176
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda