DEV Community

Cover image for Differentiating onclick and addEventListener in JavaScript
Super
Super

Posted on

Differentiating onclick and addEventListener in JavaScript

Overview

This article provides an insightful examination of the contrasting approaches to event handling in JavaScript: the familiar onclick and the versatile addEventListener method. By delving into the nuances of these two mechanisms, we uncover the unique advantages they offer and the scenarios in which they excel. Through comprehensive examples and practical use cases, we'll dissect the syntax, behavior, and compatibility of both onclick and addEventListener, empowering developers to make informed choices when implementing event-driven interactions in their web applications. Whether it's a straightforward click action or a more complex event management requirement, this article equips readers with the knowledge to navigate between these two event handling paradigms effectively.

Definitions

Here are the definitions:

onclick in HTML:

onclick is an HTML attribute used to attach JavaScript code that will execute when a specific element, such as a button or a link, is clicked by the user. This attribute allows developers to define inline event handling directly within the HTML markup. When the element is clicked, the specified JavaScript code is triggered, enabling interactivity and user-initiated actions. While simple to use, onclick is limited to a single event handler and can become cumbersome when managing multiple events on the same element or handling more complex scenarios.

addEventListener in JavaScript:

addEventListener is a method in JavaScript that allows developers to dynamically attach event handlers to HTML elements. It provides a more flexible and robust approach compared to inline event attributes like onclick. With addEventListener, multiple event listeners can be added to the same element, and event handling can be more organized and maintainable. It offers control over event propagation, capturing, and bubbling phases. Additionally, addEventListener accommodates various event types beyond just clicks, expanding its utility for handling a wide range of user interactions and application behaviors.

Usage

onclick

<!DOCTYPE html>
<html>
<head>
  <title>onclick Example</title>
</head>
<body>

<button id="myButton">Click me</button>

<script>
  function handleClick() {
    alert("Button clicked!");
  }

  document.getElementById("myButton").onclick = handleClick;
</script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

In this example, the onclick attribute is used to directly assign a JavaScript function (handleClick) to the button's click event. When the button is clicked, the handleClick function is executed, displaying an alert.

addEventListener

<!DOCTYPE html>
<html>
<head>
  <title>addEventListener Example</title>
</head>
<body>

<button id="myButton">Click me</button>

<script>
  function handleClick() {
    alert("Button clicked!");
  }

  document.getElementById("myButton").addEventListener("click", handleClick);
</script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

In this example, the addEventListener method is used to attach the same handleClick function to the button's click event. This method provides more flexibility and allows for multiple event listeners to be added to the same element.

Differences

Difference between addEventListener and onclick:

addEventListener:

  • addEventListener allows the addition of multiple events to a specific element.
  • It can accept a third argument that provides control over event propagation.
  • Events added using addEventListener can only be attached within <script> elements or in external JavaScript files.
  • Compatibility may be limited, as it does not work in older versions of Internet Explorer, which use attachEvent instead.

onclick:

  • onclick is used to attach a single event to an element.
  • It is essentially a property and may get overwritten.
  • Event propagation cannot be controlled directly with onclick.
  • onclick can also be added directly as an HTML attribute, offering a simpler integration method.
  • It is widely supported and functions across various browsers.

The choice between addEventListener and onclick depends on the complexity of event management required and the compatibility needs of the application.

Conclusion

In conclusion, understanding the distinctions between addEventListener and onclick is essential for effective event handling in JavaScript. While both methods enable interaction and responsiveness, they cater to different levels of complexity and compatibility requirements.

addEventListener emerges as a versatile tool, offering the flexibility to attach multiple events to a single element. Its capacity to control event propagation and its suitability for structured scripting make it a robust choice for modern applications. However, developers should be cautious of its limited compatibility with older browsers.

On the other hand, onclick provides a straightforward means of attaching a single event to an element, making it a suitable choice for simpler interactions. Its direct integration as an HTML attribute streamlines implementation but may lack the comprehensive control and scalability offered by addEventListener.

In the end, the selection between these methods hinges on the project's scope, desired functionality, and the targeted user base. By grasping the strengths and limitations of each approach, developers can make informed decisions, crafting seamless and responsive web experiences tailored to their unique needs.

Top comments (12)

Collapse
 
ant_f_dev profile image
Anthony Fung • Edited

Great explanation.

One side point to mention - when adding event listeners in this way, be sure to remove them (using removeEventListener) if/when they're no longer required. Otherwise, you may end up with either memory leaks, unexpected behaviour, or both.

When removing a handler, be sure to pass in the same function (rather than e.g. an arrow function).

Collapse
 
efpage profile image
Eckehard • Edited

It is fairly easy to change the default behavoir to accept multiple events. You can just overwrite the existing event like this:

    // change click event to accept multiple listeners
    function multiclick(el) {
      Object.defineProperty(el, 'onclick', {
        set: function (f) { this.addEventListener('click', f) }
      })
    }

    function removeEvents(el) {
      el.replaceWith(el.cloneNode(true))
    }

    multiclick(mybutton)

    mybutton.onclick = () => alert("Hello world1")
    mybutton.onclick = () => alert("Hello world2")

    window.onunload = () => removeEvents(mybutton)
Enter fullscreen mode Exit fullscreen mode

This call both alerts on a single click.

For the sake of completeness I added the cleanup code also :-)

Collapse
 
abidullah786 profile image
ABIDULLAH786

Well explained ♥️,

In short the addEventListener is the mecganism of attaching different types of events (such as click,hover and other key events) to an HTML tag, while onClick is single responsibility Event that is specifically designed to add click event to HTML tag.

Collapse
 
miketalbot profile image
Mike Talbot ⭐

You missed one point - addEventListener requires a removeEventListener to be called to get rid of it, onclick handles this for you. Important in dynamic pages.

Collapse
 
dannyengelman profile image
Danny Engelman

That all depends where the eventhandler is attached. Any type of handler attached to Element X is garbagecollected when X is removed from the DOM.

Collapse
 
miketalbot profile image
Mike Talbot ⭐

You're quite right, the event handler will be garbage collected if nothing has a reference to it, which would occur in this case. The reason that's top of mind in my case is a convulted situation with closures that were holding things open - but that's just me.

Collapse
 
ornic profile image
Roman Orlov

"Event propagation cannot be controlled directly with onclick."

This is just wrong. There is an event variable passed to the function in the onclick attribute. And this event has .stopPropagation method.

Collapse
 
oskargrosser profile image
Oskar Grosser • Edited

You are right, propagation can be stopped in the bubbling phase. But there is no way for the listener to capture the event before it propagates to the target, which is what the third parameter of addEventListener() controls.

The article could have formulated this better.

Collapse
 
gyauelvis profile image
Gyau Boahen Elvis

How do we use addEventListener to add multiple events?

Collapse
 
omarelmoez_54 profile image
Omar Elmoez

Write it twice
Btn.addEventListener('click', () => {
console.log(1);
} )
Btn.addEventListener('click', () => {
console.log(2);
} )
You can't do this with onclick

Collapse
 
gyauelvis profile image
Gyau Boahen Elvis

Thanks.

Collapse
 
slaveofthecode profile image
slaveofthecode

Esto es muy junior.