There are many ways to call a JavaScript function in the HTML document, and it is also not a difficult task. First, we have used one of the easiest ways to call a JavaScript function in HTML document:
In this method, we will create and define a function in the HTML document's head section. To invoke this function in the html document, we have to create a simple button and using the title event attribute [which is an event handler] along with it, we can call the function by clicking on the button.
To understand it more clearly let's see the given program:
Program
Explanation of program
In the above-given program, we have created a simple HTML document. Inside the head section of the HTML document, we have defined a function [e.g myfunction[];] inside the script tags ....
On the other hand, inside the body section, we displayed some text and created a button. To call our function, we have used the title attribute along with the button and when the user clicks on that button our function gets executes and display an alert message, as you can see in the output.
Output
Google MapsAnimated Buttons
Modal Boxes
Animations
Progress Bars
Hover Dropdowns
Click Dropdowns
Responsive Tables
Include the HTML
Including HTML is done by using a w3-include-html attribute:
Example
Add the JavaScript
HTML includes are done by JavaScript.
Example
function includeHTML[] {
var z, i, elmnt, file, xhttp;
/* Loop through a collection of all HTML elements: */
z = document.getElementsByTagName["*"];
for [i = 0; i < z.length; i++] {
elmnt = z[i];
/*search for elements with
a certain atrribute:*/
file = elmnt.getAttribute["w3-include-html"];
if [file] {
/* Make an HTTP request using the attribute value as the file name: */
xhttp = new XMLHttpRequest[];
xhttp.onreadystatechange = function[] {
if [this.readyState == 4] {
if [this.status == 200] {elmnt.innerHTML = this.responseText;}
if [this.status == 404] {elmnt.innerHTML = "Page not found.";}
/* Remove the attribute, and call this function once more: */
elmnt.removeAttribute["w3-include-html"];
includeHTML[];
}
}
xhttp.open["GET", file, true];
xhttp.send[];
/* Exit the function: */
return;
}
}
}
Call includeHTML[] at the bottom of the page:
Include Many HTML Snippets
You can include any number of HTML snippets:
Example
Try it Yourself »