Computer >> Computer tutorials >  >> Programming >> Javascript

How to call a JavaScript function on a click event?


JavaScript's interaction with HTML is handled through events that occur when the user or the browser manipulates a page.

When the page loads, it is called an event. When the user clicks a button, that clicks to is an event. Other examples include events like pressing any key, closing a window, resizing a window, etc.

The onclick() event occurs when a user clicks the left button of his mouse. Place your validation, warning etc., against this event type.

How to call a JavaScript function on a click event?

Example

You can try to run the following code to call a JavaScript function on a click event −

<html>
   <head>
      <script>
         <!--
            function sayHello() {
               alert("Demo Alert")
            }
         //-->
      </script>
   </head>
   <body>
      <p>Click the following button and see result</p>
      <form>
         <input type="button" onclick="sayHello()" value="Click" />
      </form>
   </body>
</html