-1

I want to have a random number different when I "click" on my button #roll, but I always get the same number. someone could help me please?

this is my code:

//création nombre aléatoire
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max, min + 1)+ min);
}
numberRandom = getRandomInt(1, 7)

//création du lancé de dé
const roll = document.getElementById("roll")
roll.addEventListener('click',()=>{
  alert(numberRandom)
})
          <button class="favorite styled" type="button" id="roll">
          Lancer le dé
          </button>
Jeff Holt
  • 2,940
  • 3
  • 22
  • 29
steph
  • 45
  • 1
  • 8
  • This looks like a duplicate of [this](https://stackoverflow.com/q/4959975/1707353). It does't explain why yours is broken but I'm guessing you'd rather have the correct code than an explanation. – Jeff Holt Jan 15 '21 at 16:13
  • `Math.floor(Math.random() * (max, min + 1)+ min);` makes no sense. Did you mean `Math.floor(Math.random() * (max - min + 1)+ min);`? – r3mainer Jan 15 '21 at 16:32
  • https://stackoverflow.com/a/1527820/7924858 – abhinavsinghvirsen Jan 15 '21 at 16:33

3 Answers3

0

Your problem is that numberRandom = getRandomInt(1, 7) is run once when the page is loaded. If you want a different number each button click, just move it inside the event listener

const roll = document.getElementById("roll")
roll.addEventListener('click',()=> {
  numberRandom = getRandomInt(1, 7)  // <=== move it here
  alert(numberRandom)
})

Additionally, the calculation doesn't not appear to be correct, I believe it should be closer to

Math.floor(Math.random() * (max - min + 1)) + min
Adam
  • 35,919
  • 9
  • 100
  • 137
0

If you want to generate a random number when you click then you need to put the code that generates a random number in the function that gets called when you click.

Putting it straight in the top level of the script means you generate a random number once as the page loads.

Every time the function gets called you read the same number from the roll variable.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min+1) ) + min;
}

const roll = document.getElementById("roll")
roll.addEventListener('click',()=>{
  var numberRandom = getRandomInt(1, 6)
  console.log('Dice rolled ,you got ',numberRandom);
})
<button class="favorite styled" type="button" id="roll">
   Role dice
</button>
Vijay Patidar
  • 461
  • 7
  • 8