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>
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.

3

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:

1
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");

1

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>

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like