How to call JavaScript function in HTML ?
In HTML, you can easily call JavaScript functions using event attributes like onclick
and onload
. Just reference the function name within these attributes to trigger it.
You can also call functions directly within script blocks using standard JavaScript syntax.
Let's create an HTML structure with some function defined in the script tag.
<!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
You can embed JavaScript directly within HTML elements using attributes like onclick
or onmouseover
. This method allows for quick implementation but can lead to mixed code and maintenance challenges.
Example: This example uses Inline Event Handling with the help of onclick attribute in a button.
<!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:

2. Using Event Listeners to call function in HTML
For a cleaner approach, use event listeners like addEventListener
to call JavaScript functions. This technique binds functions to specific events, such as click
or mouseover
, keeping the behavior separate from the structure and making the code easier to maintain.
Example: In this example, we are using Event Listeners
<!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:
