Amauri
Amauri

Reputation: 550

Event handler not working with JavaScript

This is a much simpler and modified part of my original code.


Anytime I call an event it doesn't function, I have tried too many times. Any help would be appreciated.

   <script type="text/javascript">
    function hello ()
    {
        alert("Hello!!!");
    }
</script>
<div id="platform">
    <div id="mainOval">
        <form id="btns">
            <input type="button" value="Timer" id="timerBtn" onclick=hello()/>
            <input type="button" value="Countdown" id="ctDownBtn" onclick=hello()/>
        </form> 
    </div>
</div>

Upvotes: 1

Views: 46

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206618

Actually,

  • don't use inline on* JavaScript handlers like onclick, it's considered unsafe and hard to debug. JavaScript scripts should be in one place only, and those are the respective tags or files. Instead, use addEventListener
  • semantics-wise, use rather <button type="button"> instead of <input type="button">
  • place your non-defered <script>s in a non-blocking manner, right before your closing </body> tag. Not in head and not anywhere else.

<body>
  <div id="platform">
    <div id="mainOval">
      <form id="btns">
        <button type="button" id="timerBtn">Timer</button>
        <button type="button" id="ctDownBtn">Countdown</button>
      </form> 
    </div>
  </div>

  <script>
  function hello () {
    alert("Hello!!!");
  }
    
  document.querySelectorAll("#timerBtn, #ctDownBtn").forEach(elBtn => {
    elBtn.addEventListener("click", hello);
  });
  </script>
</body>

Additional resources:

Upvotes: 1

Cristian E.
Cristian E.

Reputation: 3583

It should be :

onclick="hello()" instead of onclick=hello()

you could even use it as

onclick="alert('Hello')"

Upvotes: 1

Related Questions