Home > database >  Why Math.random method does not work in my case
Why Math.random method does not work in my case

Time:09-03

I am using the Dom domination to create a function that will be executed if someone clicks the button 'again'. The function is about creating a new random number that is assigned to the 'secret' variable. Unfortunately, when I click the button 'again' on the website, the value of the 'secret' variable does not change. Somebody help me, please!

let secret = Math.trunc(Math.random() * 20)   1;
document.querySelector('.again').addEventListener('click', function () {
  secret = Math.trunc(Math.random() * 20)   1;
});

CodePudding user response:

It's working .. there is nothing wrong with it

Consider logging the value or using it in the DOM to watch changes

let secret = Math.trunc(Math.random() * 20)   1;
const span = document.querySelector("#secret");

span.innerText = `${secret} initially`;

document.querySelector('.again').addEventListener('click', function() {
  secret = Math.trunc(Math.random() * 20)   1;
  console.log(secret);
  span.innerText = secret;
});
<h1> Value = <span id="secret"></span> </h1>
<button >Click Me</button>

CodePudding user response:

Thank you! I solved my problem. The secret number actually changed but I did not recognize that since I log the secret variable to the console outside the function. Therefore, the console.log is not executed when I click the button Again.

  • Related