In this article, some light will be shed on how a function that exists in JavaScript, can be accessed by the HTML section.
Calling any JS Function within HTML code
When tackling functions in JavaScript, two distinct scenarios will stand out. This section will show you how you can call any JavaScript function in either of those two cases.
JavaScript inside the HTML File
When the JavaScript function exists within the same file as the HTML code, it is fairly simple to access it and call it within HTML. Let us see the sample code below:
<head>
<script type = "text/javascript">
function sampleFunction() {
alert("This function is working!");
}
</script>
</head>
<body>
<h1>Click this button to Call the JavaScript function inside HTML</h1>
<input type = "button" onclick = "sampleFunction()" value = "Press me!">
</body>
</html>
Within the JavaScript section of this code, a function is formed that has the name “sampleFunction”. The function is supposed to execute an alert when called. Within the main body of the HTML code, a button is created. Buttons have an “onclick” feature that allows them to call functions from the JS code. We will utilize the name “sampleFunction” which will be used to call it in the “onclick” feature. Check out the example below:
The output is as follows:
JavaScript Inside an External File
In most cases, JavaScript functions are not present within the same file as the HTML code. In cases like this, the two files need to be linked together so that the HTML code can call functions from JavaScript. This code down below represents JavaScript file:
document.write("Function has been called!");
}
In the JavaScript file, the function has been created. This function can now be called in an HTML file as many times as the developer desires. The code below shows the HTML file:
<head>
<script type = "text/javascript" src = "jsFile.js"></script>
</head>
<body>
<h1>Click this button to Call the JavaScript function inside HTML</h1>
<input type = "button" onclick = "sampleFunction()" value = "Press me!">
</body>
</html>
Here we have linked the JavaScript file that is named “jsFile.js” with the HTML file using the “src” keyword within the script tags. Doing this will allow the “onclick” function below to access the function from the JS file.
Conclusion
There are two ways to reach a JavaScript function within HTML. The first is to use the “onclick” feature of a button to call the function which is already present inside the HTML file. The second one is linking the external JavaScript file with the HTML file using the “src” keyword. In this article, you have learned the two different scenarios in which you will need to access a function from JavaScript inside HTML.