How to call a JavaScript function in HTML?


In this article, we will be exploring the calling and initialization of the JavaScript function from an HTML template. We require the JavaScript function to execute the desired methods over the input passed.

In this tutorial, we will be discussing two major approaches to calling a JavaScript function from an HTML page.

In the first Approach, we are going to take a simple input tag and a Submit button associated with it. Once the button is clicked we will see a dialog box that pops up on the screen as an alert. This button on click calls invokes the JavaScript function to show the alert.

Approach 1

  • First, take a button by the input tag.

  • After clicking the button, you can see a dialog box that pops up on the screen that has already been declared in the JavaScript function as an alert.

  • The clickEvent() function allows executing the alert() when this button gets clicked by using onclick() method.

Example 1

# index.html

<!DOCTYPE html>
<html>
<body>
   <h1 style="color: green;">
      Welcome To Tutorials Point
   </h1>
   <input type="button" onclick="clickEvent();" value="Click Here !" />
   <script>
      function clickEvent() {
         alert("Hey... The Javascript function is invoked.");
      }
   </script>
</body>
</html>

Output

The above program will produce the following result. When you click the "Click Here !" button, it will alert with the message "Hey… the Javascript function is invoked."

Approach 2

In this approach, we could use JavaScript to write HTML directly. We can add all our template code inside the script tag and write to the template using the document.write() method. Similarly, we can also use the JavaScript functions directly from the HTML template without the use of any event.

Example 2

# index.html

<!DOCTYPE html>
<html>
<head>
   <title>Calling JavaScript function in HTML</title>
</head>
<body>
   <script>
      function display() {
         document.write("<h1 style='color:green;'>Welcome to Tutorials Point</h1>");
         document.write("<h3>Writing this text from Javascript</h3>");
      }
      display();
   </script>
</body>
</html>

Output

The output of the above program is as below screenshot −

Updated on: 22-Apr-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements