Skip to main content

How does onclick differ from addEventListener()?

1. The main difference

CharacteristiconclickaddEventListener()
Number of handlersOnly one - a new one overwrites the old oneYou can add several
RemovalJust assign nullVia removeEventListener()
FlexibilityOnly one event (e.g. onclick)Any event: click, keydown, scroll, input, customEvent
Extra optionsNoneAvailable (once, capture, passive)
CompatibilityOld, supported everywhereModern, supported in all modern browsers

2. Example: overwriting a handler

javascript
const btn = document.querySelector('#btn'); // first handler btn.onclick = () => console.log('First'); // second handler btn.onclick = () => console.log('Second');

In the end, clicking only outputs

javascript
Second

because the second one overwrote the first.

But with addEventListener() both fire:

javascript
btn.addEventListener('click', () => console.log('First')); btn.addEventListener('click', () => console.log('Second'));

On click:

javascript
First Second

3. Example of removing a handler

With onclick:

javascript
btn.onclick = null; // removes the handler

With addEventListener:

javascript
function handler() { console.log('click'); } btn.addEventListener('click', handler); btn.removeEventListener('click', handler);

4. Example with options (available only with addEventListener)

javascript
btn.addEventListener('click', handler, { once: true });

The handler fires only once and is automatically removed. This is not possible with onclick.

5. You can assign any events

With onclick you can only use "click", but with addEventListener you can use any type, even a custom one:

javascript
element.addEventListener('myCustomEvent', () => console.log('custom event!'));

6. An example of the difference in HTML

You can add a handler right in HTML:

javascript
<button onclick="alert('Hello')">Click</button>

But this is not recommended - it mixes structure (JS inside HTML) and is hard to maintain. Modern practice is to always use addEventListener() in JS.

Summary

onclickaddEventListener()
Can assign multiple handlersNoYes
Can control behavior (once, capture)NoYes
Can listen for any eventsClick onlyAny
Can be used directly in HTMLYesNo
Modern standardLegacyRecommended

Conclusion: onclick is a simple but outdated way, fine for small tasks. addEventListener() is the modern, flexible, and correct way to assign events in JavaScript.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.