[SOLVED] JavaScript button onclick not working

Issue

<button onclick="hello()">Hello</button>

<script>
  function hello() {
    alert('Hello');
  }
</script>

This is my code. But it’s not working. When I click on the button nothing happens.

Solution

How about this?

<button id="hellobutton">Hello</button>
<script>
function hello() {
alert('Hello');
}
document.getElementById("hellobutton").addEventListener("click", hello);
</script>

P.S. You should place hello() above of the button.

Answered By – Kangjun Heo

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.