0

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>
vish130
  • 3
  • 2

1 Answers1

0

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>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • Ohh I see, very neat. Yeah i'm going through tutorials centered around onclick, very useful to know it's an older technique. I'll make sure to use the .addEventListener method in the future to facilitate the handling of the event. – vish130 Jun 23 '20 at 01:36