Call a JavaScript Function From HTML

Call a JavaScript Function From HTML | It is not a big challenge, and there are many ways to invoke a JavaScript function in an HTML document. The first method we used to invoke a JavaScript function in an HTML document is one of the simplest:

In this approach, a function will be created and defined in the head section of the HTML content. Create a straightforward button in the HTML document and add the onclick event attribute (an event handler) to it so that the function may be called when the button is clicked. Also see:- JavaScript Check If Variable Is Undefined

Example:- Call a JavaScript Function From HTML

Let us write a program to understand the above-said things. We can define the JavaScript function inside the HTML file itself.

<html>
  <head>
    <script type="text/javascript">
      function myfunction() {
        alert("Hello World");
      }
    </script>
  </head>
  <body>
    <p>Click the following button to see the function in action</p>
    <input type="button" onclick="myfunction()" value="Display" />
  </body>
</html>

After clicking on the “Display” button you will get the following response.

Call a JavaScript Function From HTML

Here, we produced a straightforward HTML document. We have defined a function (for example, myfunction();) inside the script tags <script>…/script> in the head part of the HTML text.

<head>
  <script type="text/javascript">
    function myfunction() {
      alert("Hello World");
    }
  </script>
</head>

On the other hand, we constructed a button and showed some text inside the body area. The onclick property is used to call our function along with the button, and when the user clicks that button, the result shows that our function is called, and an alert message is displayed.

<body>
  <p>Click the following button to see the function in action</p>
  <input type="button" onclick="myfunction()" value="Display" />
</body>

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *