Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

175
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!