Call JavaScript function from HTML

In this article, we will look at different methods to call JavaScript functions from HTML files. You can use either of these methods depending on your use case. Before that, let us understand why exactly would we want to use javascript on an HTML page.

Table of Contents

  • Why is JavaScript used along with HTML?
  • Using the script tags
  • Inline in the HTML
  • External Files
  • Other Related Concepts

Why is JavaScript used along with HTML?

While HTML and CSS help us with displaying static information on a webpage, using JavaScript makes the page interactive. Using JavaScript enables the user to implement complex features on web pages such as interactive maps, animated 2D/3D graphics, scrolling video jukeboxes, etc. Let us now look at the different methods to call JavaScript functions from HTML pages.

Using the script tags

This is one of the easiest methods and is more useful when you have fewer lines of code in your JavaScript function. In this method, we would first create and define a function in the head section of the HTML document between the tags.. This function is later invoked in the body of the HTML document.

Example:
<html>
   <head>
      <script type="text/javascript">
         var myVar="hello";
         function exampleFunction() { alert('You triggered an alert!'); }
      </script>
   </head>
   <body>
      <p><a href="#" onClick="exampleFunction;">Click Me</a></p>
   </body>
</html>

Inline in the HTML

In this method, we define the Javascript function inside the body of the function. Using this method is not considered to be a best practice.

Example:
<style type="text/css">
   .red { border: 2px solid red; }
   .blue { border: 2px solid blue; }
</style>
<p><img name="photo" src="/examples/photo.jpg" 
   onMouseOver="photo.setAttribute('class','red')" 
   onMouseOut="photo.setAttribute('class','blue')"></p>

In the above example, we use an inline JavaScript function to change the border color of a picture when we hover over it.


External Files

This is the most used & preferred method out of the three. In this method, we define the scripts in a separate file and link them using the src attribute of the script tag in the head section of the HTML document. The type must be set to text\javascript. The external javascript file would have a .js extension.

Example:
External Script file: function.js
function exampleFunction() {
    alert('You triggered an alert!');
}

HTML File:
<html>
   <head>
      <script type = "text/javascript" src="function.js"></script>  
   </head>
   <body>
      <p><a href="#" onClick="exampleFunction;">Click Me</a></p>
   </body>
</html>