Onclick JavaScript: onclick vs addEventListener for Handling JavaScript Events

Onclick JavaScript: onclick vs addEventListener for Handling JavaScript Events

Use addEventListener for most click handling, and save onclick for tiny demos or quick tests. It keeps HTML cleaner. It also lets many scripts listen to the same click without fighting each other. MDN describes addEventListener() as the standard way to set up event handlers on targets like buttons, links, and the document [source: MDN].

TLDR: onclick is quick and easy, but addEventListener is safer and more flexible. If a shop button needs to track analytics, open a cart, and show a coupon, addEventListener can run all 3 actions from one click. In a small test page with 20 buttons, inline onclick may feel fine. In a real app with 200 buttons, it gets messy fast.

The simple version

A click event is just the browser saying, “Hey, the user poked this thing.” JavaScript hears that poke and runs code.

You can handle that poke in two common ways:

  • onclick: Put the click handler right on the element or assign it as a property.
  • addEventListener: Attach a listener with JavaScript.

Both work. Both can run a function. But they do not age the same.

What is onclick?

onclick is the old-school way. It is simple. It is direct. It is also very easy to outgrow.

Here is inline onclick:

<button onclick="sayHi()">Say hi</button>

<script>
function sayHi() {
  alert("Hi!");
}
</script>

This is friendly for beginners. You can see what happens right on the button. No mystery. No hunt.

You can also use onclick in JavaScript:

const button = document.querySelector("button");

button.onclick = function () {
  alert("Hi!");
};

Still simple. Still readable. But here comes the annoying bit.

If you assign onclick again, the old one gets replaced.

button.onclick = function () {
  console.log("Open cart");
};

button.onclick = function () {
  console.log("Track click");
};

Only “Track click” runs. The cart does not open. Great. Now you get to lose 12 minutes wondering why your button suddenly became lazy.

What is addEventListener?

addEventListener is the modern favorite. It attaches a listener to an element. It can attach many listeners to the same event.

const button = document.querySelector("button");

button.addEventListener("click", function () {
  alert("Hi!");
});

That code says: “When this button gets clicked, run this function.”

Now add more work to the same click:

button.addEventListener("click", function () {
  console.log("Open cart");
});

button.addEventListener("click", function () {
  console.log("Track click");
});

button.addEventListener("click", function () {
  console.log("Show coupon");
});

All three run. Nobody gets kicked out. That is the big win.

Quick comparison

Feature onclick addEventListener
Easy for tiny examples Yes Yes
Keeps HTML clean No Yes
Allows many handlers No, one property wins Yes
Good for large apps Not really Yes
Can remove handler cleanly Sort of Yes

Why inline onclick gets messy

Inline onclick mixes HTML and JavaScript. That looks harmless at first.

<button onclick="openCart(); trackClick(); showCoupon();">
  Buy now
</button>

But then the button grows tentacles. One more function. Then another. Then a condition. Then a user role check. Suddenly your HTML looks like it had three coffees and no sleep.

It also makes testing harder. It makes reuse harder. And if your JavaScript file changes, you may still need to edit the HTML. That is extra clicking. Nobody asked for that.

Why addEventListener feels cleaner

With addEventListener, your HTML can stay calm.

<button id="buyButton">Buy now</button>

Your JavaScript does the behavior work:

const buyButton = document.querySelector("#buyButton");

buyButton.addEventListener("click", openCart);
buyButton.addEventListener("click", trackClick);
buyButton.addEventListener("click", showCoupon);

That reads like a little checklist. Nice. Clear. Boring in a good way.

Removing click handlers

Sometimes you need to stop listening. Maybe a popup closed. Maybe a game ended. Maybe a button should work only once.

With addEventListener, use removeEventListener. But save the function reference.

function handleClick() {
  console.log("Clicked");
}

button.addEventListener("click", handleClick);

button.removeEventListener("click", handleClick);

This works because the browser can match the same function.

This does not work well:

button.addEventListener("click", function () {
  console.log("Clicked");
});

button.removeEventListener("click", function () {
  console.log("Clicked");
});

Those look the same to humans. To JavaScript, they are two different functions. Honestly, it feels like a tiny prank.

The once option is lovely

addEventListener can take options. One of the best is once. It runs the handler one time, then removes it.

button.addEventListener("click", function () {
  console.log("This runs once");
}, { once: true });

This is great for welcome messages, one-time payments, confirmation clicks, and tutorials.

Event bubbling, in plain words

Clicks can bubble upward. If you click a button inside a card, the button gets the click first. Then the card can hear it. Then the page can hear it.

This is useful. You can listen on a parent instead of adding listeners to 100 child buttons.

const list = document.querySelector("#productList");

list.addEventListener("click", function (event) {
  if (event.target.matches("button")) {
    console.log("Product button clicked");
  }
});

This pattern is called event delegation. It is handy for lists, menus, tables, and search results that change after the page loads.

When should you use onclick?

Use onclick when the page is tiny and the code is for learning.

  • A quick demo.
  • A classroom example.
  • A throwaway test.
  • A single button on a simple page.

That is fine. No shame. We all make tiny test buttons called “Click me” and pretend they are serious software.

When should you use addEventListener?

Use addEventListener for almost everything else.

  • Real websites.
  • Apps with many buttons.
  • Code shared by a team.
  • Analytics tracking.
  • Popups, menus, sliders, tabs, and forms.
  • Any code that may grow later.

If your feature has more than one job, pick addEventListener. If another developer may touch it next month, pick addEventListener. If future you may forget what you wrote, definitely pick addEventListener.

A tiny real-world example

Imagine a pizza site. The “Order” button must do four things:

  1. Add pizza to the cart.
  2. Update the cart count.
  3. Send an analytics event.
  4. Show a happy little message.

With onclick, one function may become a giant junk drawer.

With addEventListener, each job can stay separate:

orderButton.addEventListener("click", addPizza);
orderButton.addEventListener("click", updateCartCount);
orderButton.addEventListener("click", sendAnalytics);
orderButton.addEventListener("click", showMessage);

That is easier to read. Easier to test. Easier to fix when the cheese icon breaks for no sane reason.

Best practice

Default to addEventListener. It is cleaner. It scales better. It lets more than one handler respond to the same event.

onclick is not evil. It is just limited. Treat it like training wheels. Useful at first. Awkward once things speed up.

So yes, the rule is simple: use onclick for quick experiments, and use addEventListener for real work. Your buttons will behave. Your code will breathe. Your future self may even say thanks.