Open In App

HTML onclick Event Attribute

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

The onclick event attribute in HTML works when the user clicks on the button. When the mouse clicked on the element then the script runs. It basically executes a script or function on a click event and is used for interactive elements like buttons and links.

Syntax

<element onclick = "script">

Attribute Value

This attribute contains a single value script that works when the mouse clicked on the element.

Example 1:

This example shows the simple onClick event where the button is clicked to display the date & time in HTML.

HTML




<!DOCTYPE html>
<html>
<style>
    body{
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        font-family: sans-serif;
    }
    h2{
        color: green;
    }
</style>
<body>
    <h2>GeeksforGeeks</h2>
    <h3>onClick Event Attribute</h3>
    <span>
        Click the button to see the date & time.
    </span>
    <button onclick="getElementById('time').
    innerHTML= Date()">
        Show Date
    </button>
    <p id="time"></p>
 
</body>
 
</html>


Output:

ae

Output

Example 2:

In this example, when the “Click Here” will be clicked then the text “Welcome to GeeksforGeeks” will be displayed.

HTML




<!DOCTYPE HTML>
<html>
 
<head>
    <title> onclick event attribute </title>
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            font-family: sans-serif;
        }
 
        h2 {
            color: green;
        }
    </style>
</head>
 
<body>
    <h2>GeeksforGeeks</h2>
    <h3>onClick Event Attribute</h3>
 
    <!-- onclick event call here -->
 
    <p id="geeks" onclick="onclick_event()">
        Click Here
    </p>
    <script>
 
        /* If onclick event call then
           this script will run */
 
        function onclick_event() {
            document.getElementById("geeks").innerHTML =
                "Welcome to GeeksforGeeks!";
        }
    </script>
</body>
 
</html>


Output:

ad

Output

Supported Tags

It supports All HTML elements, EXCEPT below listed elements:

Supported Browser

  • Google Chrome 1 and above
  • Edge 12 and above
  • Firefox 6 and above
  • Opera 11.6 and above
  • Safari 3 and above


Last Updated : 20 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads