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> 2 5 Answers
Just set the onclick event of the element to null after the first trigger:
<button onClick="yumpizza();">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.
Add one more line to yumpizza() function:
document.getElementById("pizzaButton").disabled = true; 1 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:
1const button = document.querySelector("#pizzaButton");
button.addEventListener("click", ev => { ev.currentTarget.textContent}, { once: true });// or 1: event.currentTarget.setAttribute("disabled", "disabled"); // 2: button.currentTarget.setAttribute("disabled", "disabled");
1Try this:
<script>
var strength = Math.floor(Math.random() * 20 + 1);
function yumpizza() {
document.getElementById("pizza").innerHTML = ("Strength:" + strength);
document.getElementById("pizza").disabled = true;
}
</script>