How to call JavaScript function in html?

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 onclick 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 onclick 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

How to call JavaScript function in html

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

Click the following button to see the function in action

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 onclick 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

How to call JavaScript function in html

Now click on the given button:

How to call JavaScript function in html
Next TopicHow to write a function in JavaScript




Hot Tutorials

Contact US

Email:[email protected]

How to call JavaScript function in html
10/30