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! Roll for Strength Var...
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>
5 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.
Add one more line to yumpizza() function:
document.getElementById("pizzaButton").disabled = true;
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:
const 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");
Try this:
<script>
var strength = Math.floor(Math.random() * 20 + 1);
function yumpizza() {
document.getElementById("pizza").innerHTML = ("Strength:" + strength);
document.getElementById("pizza").disabled = true;
}
</script>