javascripthtmlfunctionbuttononclick

JavaScript button onclick not working


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