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)
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>
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.