In this article, we will discuss how to call an external javascript function from an HTML button. This is a common question that arises for developers who are new to javascript. We will provide a full example of how to do this, and explain the code in detail. Let’s get started!
Inline JavaScript function
Call the JavaScript function in HTML is the first approach. This needs to be done by creating a function and then placing it in the head or body of the HTML document. In order for this code to execute, you may either create a link or a button, then add an onclick() event.
Now we’ll give you a quick walkthrough. This example includes a very basic HTML file with the functionName() method defined in script tags at the top of the HTML, as shown below.
Example
<html>
<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>
Call JavaScript function through external files
The second approach is to utilize external JavaScript files. External JavaScript files are included in the HTML document’s header. To begin, you must first create two files: a .html file in which HTML code is written and a .js file in which functions are defined.
Once we’ve completed the JavaScript development, we must create an HTML file. We must either establish a link or a button after adding the JavaScript file, then call the function defined in the script.
Example
The “jsarticle.js” file, which is included in the installation folder and contains a single JavaScript function for each article (for example, “articl1”)
<html>
<head>
<script type = "text/javascript" src="jsarticle.js"></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>
Jsarticle.js
Jsarticle.js
function functionName() {
document.write("You are learning how to call JavaScript function in html");
}
The JavaScript files must be in the same folder as the HTML and CSS files, unless the site is being served from a subdirectory. In our example, because we stored all of the HTML and JavaScript files in the same folder, we have named only one of them “js” rather than providing a complete path.
<body>
<h4>Hey, click on the button below to invoke the function</h4>
<input type = "button" onclick = "functionName()" value = "Click Me">
</body>
Conclusion
We’ll show you how to call JavaScript functions in HTML in this post. We’ve also gone over two methods. We are including a JavaScript file within an HTML document using the first approach. We are calling JavaScript from external files using the second approach. Both of these approaches have been outlined, as well as example code for calling JavaScript functions in HTML.