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());