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
Calling a function using external JavaScript file
We can also call JavaScript functions using an external JavaScript file attached to our HTML document. To do this, first we have to create a JavaScript file and define our function in it and save itwith [.Js] extension.
Once the JavaScript file is created, we need to create a simple HTML document. To include our JavaScript file in the HTML document, we have to use the script tag and in the "src" attribute we have to provide the path to our JavaScript file where it is stored. After linking the external JavaScript file to the HTML document, we can create a button and call the function using the " title" attribute with it.
Let's understand it with help of a program:
Program
Explanation of program
In the above program first, we have created a JavaScript file and defined our function in it and saved it with the .js extension.
Function.js
After creating the JavaScript file, we have created an HTML document and linked our JavaScript file using . Because we have stored our HTML document and JavaScript file in the same folder, we have just named our JavaScript file in the "scr" attribute instead of providing the full path in the head section.
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
Now click on the given button:
Roudra
12:03 pm on Nov 25, 2008 [gmt 0]
Hi, i am trying to call a javascript function from within a div tag on click of it. while calling the function i intend to pass the id of the div as an object to the called function. I have the below code in HTML.Using this code, when i click on the DIV in the HTML, the javascript function is not getting called. Please advise...
Templates
Landing Page