The Wayback Machine - https://web.archive.org/web/20240306100721/https://www.geeksforgeeks.org/how-to-call-javascript-function-in-html/
Open In App
Related Articles

How to call JavaScript function in HTML ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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:

1

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:

2



Last Updated : 16 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads