What is onclick event in JavaScript?

The onclick event is one of the most frequently used JavaScript events. It triggers when a user clicks an HTML element, typically with the left mouse button.

Syntax

The onclick event can be added in three ways:

// Method 1: Inline HTML attribute
<button onclick="functionName()">Click Me</button>

// Method 2: Element property
element.onclick = function() { /* code */ };

// Method 3: Event listener (recommended)
element.addEventListener('click', function() { /* code */ });

Example: Inline onclick

The simplest approach is using the onclick attribute directly in HTML:

<html>
<head>
   <script>
      function sayHello() {
         alert("Hello World!");
      }
   </script>
</head>
<body>
   <p>Click the following button and see result</p>
   <form>
      <input type="button" onclick="sayHello()" value="Say Hello" />
   </form>
</body>
</html>

Example: Using Element Property

You can assign the event handler using JavaScript:

<html>
<head>
   <script>
      function setupButton() {
         const btn = document.getElementById('myButton');
         btn.onclick = function() {
            alert('Button clicked via property!');
         };
      }
   </script>
</head>
<body onload="setupButton()">
   <button id="myButton">Click Me</button>
</body>
</html>

Example: Using addEventListener (Recommended)

The modern approach uses addEventListener() for better flexibility:

<html>
<head>
   <script>
      function setupEventListener() {
         const btn = document.getElementById('modernButton');
         btn.addEventListener('click', function(event) {
            console.log('Modern click event triggered!');
            console.log('Clicked element:', event.target.tagName);
         });
      }
   </script>
</head>
<body onload="setupEventListener()">
   <button id="modernButton">Modern Click</button>
</body>
</html>

Comparison

Method Multiple Handlers Event Object Best Practice
Inline onclick No Limited Quick testing only
Element property No Yes Simple scenarios
addEventListener Yes Yes Recommended

Common Use Cases

The onclick event is commonly used for:

  • Form validation and submission
  • Show/hide content toggles
  • Navigation and menu interactions
  • Modal dialogs and popups
  • Dynamic content updates

Conclusion

The onclick event is essential for interactive web pages. Use addEventListener() for modern applications, as it supports multiple handlers and provides better event control.

Updated on: 2026-03-15T22:05:42+05:30

715 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements