HTML onclick Event Attribute
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 onclick = "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 1
- Microsoft Edge 12
- Firefox 6
- Internet Explorer 9
- Safari 3
- Opera 11.6
Please Login to comment...