onclick
onclick event
The onclick
event attribute activates a JavaScript function when an element is clicked. It is frequently used with buttons, links, and other interactive elements. To use it, add the attribute to the element and define the script
to execute upon the click.
Syntax
In HTML
<element onclick="myScript">
In JS
object.onclick = function(){myScript};
addEventListener()
function is used. In JavaScript, the
object.addEventListener("click", myScript);
Example
<!DOCTYPE html>
<html>
<body>
<h1>HTML DOM Events</h1>
<h2>The onclick Event</h2>
<p>The onclick event triggers a function when an element is clicked on.</p>
<p>Click to trigger a function that will output "Hello World":</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script>
</body>
</html>
Values
Conclusion
The onclick
event triggers a JavaScript function when an element is clicked, often used with buttons and interactive elements. It allows developers to define actions for user interactions. This event is essential for enhancing interactivity on web pages.
Mouse
HTML mouse event attributes trigger actions based on user interactions like clicks or movements, using attributes such as onclick, onmouseover, and onmousedown.
oncontextmenu
The oncontextmenu event is triggered when a user right-clicks an HTML element to open the context menu. For more details, refer to Mouse Events.