Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

HTML onclick Event Attribute

  • Difficulty Level : Basic
  • Last Updated : 16 Dec, 2021

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.

Syntax:

<element onlick = "script">

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

Supported Tags: This attribute is supported by all HTML tags except <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title>.

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>
<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:

HTML onclick event attribute

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>
    <script>
     
    /* If onclick event call then
       this script will run */
        
    function onclick_event() {
        document.getElementById("geeks").innerHTML =
        "Welcome to GeeksforGeeks!";
    }
    </script>
</head>
 
<body>
    <h2>GeeksforGeeks</h2>
    <h3>onClick Event Attribute</h3>
   
    <!-- onclick event call here -->
   
    <p id="geeks" onclick="onclick_event()">
        Click Here
    </p>
 
 
</body>
</html>

Output:

onclick event call to run the script using the onclick event attribute

Example 3: In this example, we have used the button tag to call the event.

HTML




<!DOCTYPE html>
<html>
<head>
    <title> onclick event attribute </title>
    <script>
    document.getElementById("geeks").addEventListener("click", functionClick);
 
    function functionClick() {
        document.getElementById("geeks").innerHTML =
        "Welcome to GeeksforGeeks!";
    }
    </script>
</head>
 
<body>
    <h2>GeeksforGeeks</h2>
    <h3>onClick Event Attribute</h3>
   
    <!-- onclick event call here -->
    <button onclick="functionClick()"> Click Here </button>
    <p id="geeks"></p>
 
 
</body>
</html>

Output:

onclick event call with button tag using onclick event attribute

Supported Browser:

  • Google Chrome 93.0 & above
  • Microsoft Edge 93.0
  • Firefox 93.0 & above
  • Safari 14.1
  • Opera 79.0


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!