Home > Software design >  How do I stop my script from running on refresh and just on the OnClick?
How do I stop my script from running on refresh and just on the OnClick?

Time:07-31

This is my HTML

<h1>Random Number Generator</h1>
<span id="number">0</span>
<button id="generateBtn">Generate</button>
<script src="js/randomnumber.js"></script>

This is my Javascript

const number = document.getElementById('number');
const generateBtn = document.getElementById('generateBtn');

const randomGenerator = () => {
  const randomnumber = Math.floor(Math.random()* 10   1);
   number.textContent = randomnumber;
};

generateBtn.addEventListener('click',randomGenerator);
randomGenerator();

So, every time I refresh the page it runs the javascript again. Any tips on how I prevent this from happening again ? All the code works I just need it to work only Onclick

CodePudding user response:

in the end of the code there's randomGenerator();

so its run when you refresh the page auto not on click so remove it and keep it like this

generateBtn.addEventListener('click',randomGenerator);

CodePudding user response:

You Should Remove this randomGenerator(); from last line.

CodePudding user response:

const number = document.getElementById('number');
const generateBtn = document.getElementById('generateBtn');

const randomGenerator = () => {
  const randomnumber = Math.floor(Math.random()* 10   1);
   number.textContent = randomnumber;
};

generateBtn.addEventListener('click',randomGenerator);
<h1>Random Number Generator</h1>
<span id="number">0</span>
<button id="generateBtn">Generate</button>
<script src="js/randomnumber.js"></script>

Remove randomGenerator(); - You're calling the function once after adding the event listener. I've provided an example above.

  • Related