Definition:
An onclick event occurs when a user clicks on an element on a webpage.
After clicking, the text, color, or style of that thing can change.
It is called an onclick event. For example, if you mouse over some text and click it, the text color or style changes.
Now you will clearly understand with the help of the flowchart.
Start
|
v
User clicks on an element
|
v
Browser detects the onclick event
|
v
Is there a function assigned?
|
|-- Yes --> Run the JavaScript function
| |
| v
| Text, color, or style changes
| |
| v
| End
|
|-- No --> Nothing happens
|
v
End
Syntax:
<element onclick="JavaScript code"></element>
Example:
<!DOCTYPE html>
<html>
<head>
<title>Onclick Example</title>
</head>
<body>
<h2 id="demo">Hello India<</h2>
<button onclick="document.getElementById('demo').style.color='red'">
Click Me
</button>
</body>
</html>
Output:
