onclick

The onclick event is triggered when a user clicks on an HTML element. For more information, refer to Mouse Events.

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

index.html
<element onclick="myScript">

In JS

script.js
object.onclick = function(){myScript};

In JavaScript, the addEventListener() function is used.

script.js
object.addEventListener("click", myScript);

Example

::event-onclick ::
index.html
<!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

  • script
    • The name of the script to run when the event is triggered.

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.