Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Button Pressed Only Once

How do I make it so that using the code below, you can only click the button once, before it doesn't do anything. Thanks in advance!

 <button onClick="yumpizza();"style="position:absolute; TOP:120px; LEFT:350px">Roll for strength</button>

<script>
    var strength = Math.floor(Math.random() * 20 + 1);
    function yumpizza() {
    document.getElementById("pizza").innerHTML = ("Strength:" + strength)
}
</script>
like image 982
JakeW Avatar asked Oct 15 '25 18:10

JakeW


2 Answers

Just set the onclick event of the element to null after the first trigger:

<button id="pizzaButton" onClick="yumpizza();" style="position:absolute; TOP:120px; LEFT:350px">Roll for strength</button>

<script>
  var strength = Math.floor(Math.random() * 20 + 1);
  function yumpizza() {
    document.getElementById("pizza").innerHTML = ("Strength:" + strength);
    document.getElementById("pizzaButton").onclick = null;
  }
</script>

On the note of event handling, is is a best practice to use addEventListener to set event handlers programmatically, instead of the onclick HTML attribute.

like image 51
PitaJ Avatar answered Oct 17 '25 11:10

PitaJ


Add one more line to yumpizza() function:

document.getElementById("pizzaButton").disabled = true;
like image 42
InfiniteStack Avatar answered Oct 17 '25 09:10

InfiniteStack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!