I have a very basic piece of code, but after the code runs the button changes to undefined, how do I stop it from doing this?
<button id="buttonevent" onclick="partyTime()">What time is it?</button>
<script>
function partyTime() {
document.getElementById("buttonevent").innerHTML=alert("It's Party Time!");
}
</script>
An alert
doesn't return anything so you are setting the contents of the button
to undefiened
. Just have the alert
code without setting the button.innerHTML
.
<button id="buttonevent" onclick="partyTime()">What time is it?</button>
<script>
function partyTime() {
alert("It's Party Time!");
}
</script>
And, as you are new to this, let's break a bad habit right from the start. While you may see many bits of code that use onclick
in the HTML, you should not set up your events this way. That's a 25+ year old technique that will not die the death it deserves for so many reasons. Instead, separate your JavaScript from your HTML and do the event binding in JavaScript.
<button id="buttonevent">What time is it?</button>
<script>
// Set up the click of the button to call the partyTime function here
// in JavaScript, not from the HTML.
document.getElementById("buttonevent").addEventListener("click", partyTime);
function partyTime() {
alert("It's Party Time!");
}
</script>