- Call JavaScript function from HTML
- Table of Contents
- Why is JavaScript used along with HTML?
- Using the script tags
- Inline in the HTML
- External Files
- How to Call a JavaScript function in HTML
- Using JS functions with HTML event attributes
- How to call a JavaScript function using HTML event attributes
- Using JS functions with JavaScript event handlers
- How to call a JavaScript function using event handlers in HTML
- How to use event listeners to call a JavaScript function in HTML
- A coding sample for calling JavaScript function using event listeners
- Conclusion
- Calling javascript function from html
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
Call JavaScript function from HTML
In this article, we will look at different methods to call JavaScript functions from HTML files. You can use either of these methods depending on your use case. Before that, let us understand why exactly would we want to use javascript on an HTML page.
Table of Contents
Why is JavaScript used along with HTML?
While HTML and CSS help us with displaying static information on a webpage, using JavaScript makes the page interactive. Using JavaScript enables the user to implement complex features on web pages such as interactive maps, animated 2D/3D graphics, scrolling video jukeboxes, etc. Let us now look at the different methods to call JavaScript functions from HTML pages.
Using the script tags
This is one of the easiest methods and is more useful when you have fewer lines of code in your JavaScript function. In this method, we would first create and define a function in the head section of the HTML document between the tags.. This function is later invoked in the body of the HTML document.
var myVar="hello"; function exampleFunction() Click Me
Inline in the HTML
In this method, we define the Javascript function inside the body of the function. Using this method is not considered to be a best practice.
.red < border: 2px solid red; >.blue
In the above example, we use an inline JavaScript function to change the border color of a picture when we hover over it.
External Files
This is the most used & preferred method out of the three. In this method, we define the scripts in a separate file and link them using the src attribute of the script tag in the head section of the HTML document. The type must be set to text\javascript. The external javascript file would have a .js extension.
External Script file: function.js
How to Call a JavaScript function in HTML
In this tutorial, you’ll learn how to call JavaScript functions from HTML pages to make them interactive.
The HTML and CSS can structure a web, can give a web its appearance and responsiveness. JavaScript helps a web page interact with users and guide them to the right information. You can use JavaScript functions to build websites that respond to common user events such as clicks, keypresses, page load, mouseover.
We’ll go step-by-step to help you grasp the core Web Development concepts with easy-to-follow code samples.
Using JS functions with HTML event attributes
You can use event attributes in an HTML control to call a Javascript function when an event occurs.
HTML provides a set of such event attributes to cover a wide range of events.
Few common examples — onclick , onchange , onload , onmouseover , onmouseout and onkeydown .
Please bear in mind that HTML event attributes work with actionable controls only. Buttons and links are few examples of such controls.
This is arguably the simplest approach to call a JavaScript function from an HTML element.
How to call a JavaScript function using HTML event attributes
Let’s develop a web page that will accept the names of its users. Once a user clicks the submit button, the website will display a greetings message to the user.
We will use an HTML event attribute onclick , to make a function call when the user clicks the button. This function will greet the user with an alert message.
You will need to create an HTML and a JavaScript file to try out the example. Let’s create index.html for the HTML source code and scripts.js for JavaScript source code. We will use these source codes for later examples too with minimal changes.
The HTML source code
You can write or copy the below source code into your index.html file. This HTML source code shows a text box and a submit button. Users can enter a name in the text box.
html lang="en"> head> title> Calling Function From HTMLtitle> head> body> label for="fullName">Enter your name:label> input type="text" name="fullName" id="fullName" /> button type="submit" onclick="showAlert()"> Submitbutton> script src="/scripts.js">script> body> html>
The above example makes use of onclick event attribute within the markup for submit button. The browser calls showAlert() function if a user clicks the submit button.
The JavaScript source code
Let’s write the below source code in the scripts.js file —
function showAlert() < var name = document.getElementById("fullName").value; alert("Hello " +name +"!"); >
This function searches for an HTML text box with id as “fullName”. It fetches the user’s input and uses that to display a message.
Expected output
When in action, the web page asks end-users to enter the user’s full name. If you enter “John Collins”, the system shows a message, “Hello John Collins!”.
Using JS functions with JavaScript event handlers
JavaScript provides a set of event handler properties capable of making function calls. You can use them with JavaScript objects to call functions in an event of an HTML control.
Each of these properties corresponds to a specific event. Few common examples — onload , onclick , onmouseover , onmouseout and onkeydown . You can get a complete list from many websites on the Internet.
JavaScript event handlers work for non-actionable HTML elements too. This means you can turn even an element into a clickable control using an event handler.
JavaScript event handlers can call only one function in an event for an HTML element. This is a limitation that paves the path for Javascript event listeners to come into the picture.
How to call a JavaScript function using event handlers in HTML
We will develop a web page that will accept the names of its users. Once a user clicks the submit button, the website will display a greetings message to the user.
Here we will use a JavaScript event handler property, onclick to call a JavaScript function when a user clicks the submit button.
The HTML source code
You can write or copy below HTML source code in your HTML document, index.html . This HTML source code shows a text box and a submit button. Users can enter a name in the text box.
html lang="en"> head> title> Calling Function From HTMLtitle> head> body> label for="fullName">Enter your name:label> input type="text" name="fullName" id="fullName"/> button type="submit" id="submitButton"> Submitbutton> script src="/scripts.js">script> body> html>
The JavaScript source code
You can write or copy below source code in your JavaScript file, scripts.js
var bttn = document.getElementById("submitButton"); function showAlert() < var name = document.getElementById("fullName").value; alert("Hello " + name + "!"); > //Used onclick event handler property to call showAlert() function bttn.onclick = showAlert;
In this example, the onclick event handler calls showAlert() function. This function call happens when you click the HTML submit button.
Expected output
If you enter the name “John” and click the submit button, the system shows the message — “Hello Jhon!”.
How to use event listeners to call a JavaScript function in HTML
You can leverage JavaScript event listeners to listen to events and call functions.
An event listener method attaches an event listener with an object and calls the desired function when you trigger a particular event on the object.
This is the most powerful yet flexible approach to call functions from HTML.
JavaScript offers below two event listener methods can be used with JavaScript objects-
- addEventListener() — Adds an event handler to an HTML element and calls functions in a specified event.
- removeEventListener() — Removes an event handler from an HTML element.
You have to pass the below parameters to these JavaScript event listener methods —
- Event Name — You need to pass the actual HTML DOM event name. Example of few common events — click, change, focus, mousemove, etc.
- Function Name — You have to pass the function name here. The browser calls this function in response to the above event on the object.
- You can assign any number of event listeners to an object. Thus, you can make multiple function calls in a single event of an HTML control.
A coding sample for calling JavaScript function using event listeners
We will develop a web page that will accept the names of its users. Once a user clicks the submit button, the website will display a greetings message to the user.
Here we will use a JavaScript event listener to call a JavaScript function when a user clicks the submit button.
The HTML source code
You can write or copy below HTML source code in your HTML document, index.html . This HTML source code shows a text box and a submit button. Users can enter a name in the text box.
html lang="en"> head> title> Calling Function From HTMLtitle> head> body> label for="fullName">Enter your name:label> input type="text" name="fullName" id="fullName"/> button type="submit" id="submitButton"> Submitbutton> script src="/scripts.js">script> body> html>
The JavaScript source code
The external JavaScript file, scripts.js should have below source code —
var bttn =document.getElementById("submitButton"); function showAlert() < var name = document.getElementById("fullName").value; alert("Hello " + name + "!"); > function showWelcomeMessage() < var name = document.getElementById("fullName").value; alert("Welcome, " + name + "!"); > //Event listener method bttn.addEventListener("click", showAlert); bttn.addEventListener("click", showWelcomeMessage);
When a user clicks the submit button, the browser makes two function calls. The functions are, showAlert() and showWelcomeMessage() .
Expected output
If you enter John as input and click the submit button, the system should display two messages back to back:
Conclusion
To sum it up, here are the things you have learned in this tutorial:
- You can use HTML event attributes, JavaScript event handlers to call functions. These can call a single function in a single event of a particular control.
- The HTML event attributes work only with actionable HTML elements.
- The JavaScript event handlers work both with actionable and non-actionable controls.
- JavaScript event listener methods accept HTML DOM events. Thus they give you the flexibility to listen to a wide range of events. In addition to it, they enable you to call many functions in a single event of a control.
- The thumb rule here is, you should use an event handler property when you need to call a single function in an event of a control. In case you need many function calls in a single event, event listener methods are the things you should choose.
Get my free e-book to prepare for the technical interview or start to Learn Full-Stack JavaScript
Calling javascript function from html
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter