3

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>
JakeW
  • 103
  • 1
  • 1
  • 4
  • Does this answer your question? [How to make onclick function execute only once?](https://stackoverflow.com/questions/57641554/how-to-make-onclick-function-execute-only-once) – Ivar Jun 20 '21 at 13:36

3 Answers3

4

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.

PitaJ
  • 12,969
  • 6
  • 36
  • 55
  • 1
    @ProVideoCreator you have to accept the answer newbie ;) – webdeb Sep 09 '15 at 01:10
  • 1
    @ProVideoCreator Don't forget to accept it as the answer if it fixed your problem. Also, you may want to try using the `disabled` attribute instead, since it alters the styling of the button. – PitaJ Sep 09 '15 at 01:11
1

Add one more line to yumpizza() function:

document.getElementById("pizzaButton").disabled = true;
InfiniteStack
  • 430
  • 2
  • 9
0

You could also use jquery:

    var strength = Math.floor(Math.random() * 20 + 1);
    function yumpizza() {
    document.getElementById("pizza").innerHTML = ("Strength:" + strength)
}
$('button').on('click', function() {
    $(this).disable();
});

here is the fiddle example: http://jsfiddle.net/eugensunic/tnaZV/530/

EugenSunic
  • 13,162
  • 13
  • 64
  • 86