Skip to content

addEventListener vs onclick | Difference

  • by

JavaScript addEventListener and onclick both listen for an event and execute a callback function when a button is click. The addEventListener() method attaches an event handler to the specified element.

element.addEventListener(event, listener, capture);

And, the onclick event attribute works when the user clicks on the button.

In HTML:

<element onclick="myScript">

In JavaScript:

object.onclick = function(){myScript};

Difference between addEventListener and onclick:

addEventListeneronclick
You can add multiple events to a particular element.You can add only a single event to an element. Because It is basically a property, so gets overwritten.
Take a third argument that can control the event propagation.Event propagation can’t be controlled by onclick.
It can only be added within <script> elements or in the external JavaScript file.It can be added as an HTML attribute also.
It does not work in older versions of Internet Explorer, which uses attachEvent instead.It works in all browsers.

Examples addEventListener vs onclick

Simple example codes.

<!DOCTYPE html>
<html>
<body>

  <button id="btn">Click here</button>

  <script>
    let btn_element = document.getElementById("btn");

    // addEventListener() method multiple event handler element
    btn_element.addEventListener("click", () => {
      console.log("Task 1 addEventListener()");
    })

    btn_element.addEventListener("click", () => {
      console.log("Task 2 addEventListener()");
    });

    // onclick 
    btn_element.onclick = () => {
      console.log("Task 1 onclick");
    };

    btn_element.onclick = () => {
      console.log("Task 1 onclick");
    };
  </script>

</body>
</html>

Output:

addEventListener vs onclick JavaScript

What is the order of inline onclick vs addEventListener and why?

Answer: Consider this button:

<button id="the_button" onclick="RunOnClick();">Click</button>

This button has an inline onclick event handler. The contents of the RunOnClick function don’t matter for this question.

Let’s attach another click event listener like so:

var btn = document.getElementById('the_button');

btn.addEventListener("click", function(){
    // Do Something
});

The handler registered with addEventListener always seems to run after the inline onclick="" one.

Can I always rely on the single inline onclick handler to fire first and the addEventListener handler to fire later?

It actually designed that way and part of one of the ECMAScript specifications.

Read more: https://stackoverflow.com/questions/49805942

Do comment if you have any doubts or suggestions on this JS comparison topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading