Inline JavaScript function
The first method is to call the JavaScript function in HTML. For this, you have to create a function then define this function either in the head section or body section of the HTML document. You can either create a link or a button and then an onclick() event is associated with them in order to call this function.
Now we are going to demonstrate a simple example. This example contains a simple HTML file in which we have defined a method functionName() within script tags in the head of the HTML as shown below.
Furthermore, we created a button and associated the onclick() event with it as shown below. Subsequently, whenever the user clicks on the button the function gets invoked:
Example
<head>
<script type = "text/javascript">
function functionName() {
alert("You are learning how to call JavaScript function in html");
}
</script>
</head>
<body>
<h4>Hey, click on the button below to invoke the function</h4>
<input type = "button" onclick = "functionName()" value = "Click Me">
</body>
</html>
Output
Call JavaScript function through external files
The second method is to call a JavaScript function in HTML through external .js files. External files of JavaScript are attached in the head section of the HTML file. First of all, you need to create two files i.e. .html file in which HTML code is written and the other is .js in which functions are defined.
We have to create an HTML document once we are done with the creation of JavaScript. After incorporating the JavaScript file we have to either create a link or a button, then invoke the function defined in the JavaScript file.
Example
This example contains a simple HTML file “articl.html” in which we link the external JavaScript file “jsarticle.js”.
articl.html
Jsarticle.js
document.write("You are learning how to call JavaScript function in html");
}
Html and JavaScript files should be either saved in the same folder and if not then we have to provide a full path in the script tags present in the head section. In our provided example we have saved the HTML and JavaScript files in the same folder that is why we have provided the name of the JavaScript file instead of providing the full path.
We have created a button in the body section and besides that button, we have also used the onclick event to call a function. Now, whenever the user clicks on that button the function will be invoked which is defined in the javascript file as shown in the below-mentioned picture.
Output
Conclusion
In this article, we demonstrate how to call JavaScript functions within HTML. We have also discussed two methods. In the first method, we are including a JavaScript file within an HTML document. In the second method, we are calling JavaScript through external files. Both these methods have been briefly explained along with examples of how JavaScript functions can be invoked in HTML.