How to call JavaScript function in HTML ?
Last Updated :
07 Mar, 2024
To call JavaScript function in HTML we can directly use the event attributes like onclick and onload. Calling a function in HTML involves referencing the function name within an event attribute or script block.
Alternatively, script blocks within the HTML document can invoke the function by name using standard JavaScript syntax.
Let’s create an HTML structure with some function defined in the script tag.
HTML
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" />
< title >
Call JavaScript Function
</ title >
</ head >
< body >
< h2 >Function call using HTML</ h2 >
< script >
function myFunction() {
alert(
"Hello, this is an inline function!"
);
}
</ script >
</ body >
</ html >
|
Examples to Call JavaScript funtion in HTML
1. Using Inline Event Handling to call function in HTML
functions handling involves embedding JavaScript logic directly within HTML elements using attributes like onclick or onmouseover. While it enables quick implementation, it can lead to code mixing and maintenance issues.
Example: This example uses Inline Event Handling with the help of onclick attribute in a button.
HTML
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< title >Call JavaScript Function - Inline</ title >
</ head >
< body >
< button onclick = "myFunction()" >Click me</ button >
< script >
function myFunction() {
alert('Hello, this is an inline function!');
}
</ script >
</ body >
</ html >
|
Output:
Using Inline Event Handling
2. Using Event Listeners to call function in HTML
To call a JavaScript function in HTML, use event listeners like addEventListener. They bind functions to specific events, such as click or mouseover, separating behavior from structure for cleaner code organization and maintenance.
Example: In this example, we are using Event Listeners
HTML
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< title >Call JavaScript Function - Event Listener</ title >
</ head >
< body >
< button id = "myButton" >Click me</ button >
< script >
// Define the function
function myFunction() {
alert('Hello, this is a function attached using an event listener!');
}
// Attach an event listener to the button
document.getElementById('myButton').addEventListener('click', myFunction);
</ script >
</ body >
</ html >
|
Output:
Using Event Listeners
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...