0

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)
jarmod
  • 71,565
  • 16
  • 115
  • 122
Jacob R
  • 1
  • 1
  • Check that `document.querySelector('#roll')` actually returns a non-null result. I'm assuming that you're actually clicking some control to try and invoke this function. – jarmod Mar 03 '22 at 23:34
  • "*the event listener only runs once when the page is loaded*" How do you figure this is a result of the event listener itself? You have a call to `roll(6)` just after you've declared `roll`; why would an event listener bound on the `click` method run on page load, exactly? – esqew Mar 03 '22 at 23:34
  • 1
    When you click the button, the browser will pass the ClickEvent to your function as first argument. If you check the console, you'll find that the event listeners works perfectly fine and prints `NaN` to the console. Here's one way how to fix this: https://jsfiddle.net/ynbho8zk/ –  Mar 03 '22 at 23:36

1 Answers1

3

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.

Daniel
  • 1,392
  • 1
  • 5
  • 16
  • Please don't use arrow functions unless there's a point. They work differently and might throw off newbies who expect `this` to work. –  Mar 03 '22 at 23:41
  • I don't think anyone, especially newbies, expects this to ever work.... haha just kidding. But yeah, I agree, it is especially bad in event listeners as you can't remove them by name. – Daniel Mar 16 '22 at 07:27