HTML onclick Event Attribute
Last Updated :
26 Jun, 2024
The onclick event attribute in HTML triggers when the user clicks on an element. It executes a script or function upon a click event and is commonly 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 clicks on the element.
Example 1: Display Date & Time on Button Click
This example shows a simple onclick event where clicking the button displays the current date and time.
HTML
<!DOCTYPE html>
<html>
<head>
<title>HTML 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>HTML 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 Output
Example 2: Display Text on Click
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>HTML onclick event attribute </title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
font-family: sans-serif;
}
</style>
</head>
<body>
<h3>HTML 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:

HTML onclick Event Attribute Example Output
The onclick event attribute is a powerful tool for adding interactivity to web pages. By attaching scripts to click events on various elements, developers can create dynamic and responsive user interfaces that enhance the user experience.
Please Login to comment...