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 ClickThis 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 ClickIn 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 OutputThe 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.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4