To call JavaScript function in HTML, we have multiple approaches.
Below are the approaches used to call JavaScript function in HTML:
Approach 1: Inline Event Handling
This approach involves directly calling a JavaScript function from within an HTML tag using event attributes.
Example: In this example, we are using Inline Event Handling
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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:

Approach 2: Event Listeners
This approach involves attaching event listeners to HTML elements using JavaScript.
Example: In this example, we are using Event Listeners
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<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:

Last Updated :
16 Jan, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...