Difference between addEventListener and on-click in JavaScript


The addEventListener and the on-click event both listen for an event. Both these event methods record an event and execute a function based on that event whenever a button is clicked. Though there is a difference between both these events work.

In this article, we are going to explore the differences between the addEventListener and the on-click function in JavaScript.

1. addEventListener

The addEventListener method uses an event handler to attach it to the specified element

Syntax

element.addEventListener(event, listener, useCapture);

Parameters

  • event − Event can be defined as any valid JavaScript event. The events are generally used without the on prefix (as used in the onclick method).

  • Listener (handler function) − This defines a JavaScript function that responds to an event that occurs.

  • useCapture (Optional Parameter) − This is an optional parameter that takes an optional value that specifies whether an event should be executed in a capturing phase or a bubbling phase.

Example 1

The example program below shows that the addEventListener method can support multiple event handlers applied to the same element.

# index.html

<!DOCTYPE html>
<html>
<body>
   <h1 style="color: green;">
      Welcome to Tutorials Point
   </h1>
   <button id="btn">Click here</button>
   <h3 id="text1"></h3>
   <h3 id="text2"></h3>
   <script>
      let btn_element = document.getElementById("btn");
      btn_element.addEventListener("click", () => {
         document.getElementById("text1")
            .innerHTML = "Executed Task 1";
      })
      btn_element.addEventListener("click", () => {
         document.getElementById("text2")
            .innerHTML = "Executed Task 2";
      });
   </script>
</body>
</html>

Output

When you click on the “Click here” button, it will show ‘Executed Task 1’, ‘Executed Task 2’.

2. onClick()

The onClick() event captures the click event and then calls the desired function. The onClick event only adds a single event to an element.

Example 2

The example program below shows that we cannot control the Event Propagation by onClick (). Also, it can be added as an HTML attribute.

# filter.js

<!DOCTYPE html>
<html>
<body>
   <h1 style="color: green;">
      Welcome To Tutorials Point
   </h1>
   <button id="btn">Click here</button>
   <h3 id="text1"></h3>
   <h3 id="text2"></h3>
   <script>
      let btn_element = document.getElementById("btn");
      btn_element.onclick = () => {
         document.getElementById("text1")
            .innerHTML = "Executed Task 1";
      };
      btn_element.onclick = () => {
         document.getElementById("text2")
            .innerHTML = "Executed Task 2";
      };
   </script>
</body>
</html>

Output

When you click on the “Click here” button, it will show ‘Executed Task 2’.

Updated on: 21-Apr-2022

990 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements