0

I am trying to implement an onclick function to an html element (which results in the simulation of rolling a dice from 1 - 6) and figured out a way to that. But while I was trying to get to work, I came across a path that just wont work and I can't figure out why.

This approach is working - I just calling methods inside the eventListener and it sucessfully returns a random number between 1 & 6 in the console:

const dice = document.querySelector('.btn--roll');     
dice.addEventListener('click', function () {
      const number = Math.trunc(Math.random() * 6) + 1;
          console.log(number);
          return number;
        });

But I just can't figure out why the second approach is not working. I am defining a function beforehand and just calling it inside the eventListener. But the console wont print anything when I click on the button.

 function rollDice() {
      console.log(Math.trunc(Math.random() * 6) + 1);
    }
 const dice = document.querySelector('.btn--roll');
 dice.addEventListener('click', rollDice());
Cm21
  • 21
  • 6
  • can you put here a reproducible example? – MarcoWriteCode May 25 '22 at 17:57
  • 2
    The linked duplicate refers to `setTimeout` instead of `addEventListener`, but the same is true for both. (And for anything that expects a function reference.) You're executing the function immediately and binding the event to the *result* of the function (which is `undefined` in this case), rather than binding the event to the function itself. – David May 25 '22 at 17:57
  • 1
    `dice.addEventListener('click', rollDice);` – epascarello May 25 '22 at 17:58
  • Thanks @epascarello. That did the trick. I guess what David is the reason: I am instantly calling the function due to the parentheses – Cm21 May 25 '22 at 18:06

0 Answers0