← Back to JavaScript, page 9

javascript-0161 · Easy fresher

How do you handle DOM events in JavaScript, and what is the difference between addEventListener and an onclick property?

addEventListener attaches any number of listeners to an element for an event type, with options such as once and passive, and removeEventListener removes them using the same function reference. An onclick property holds only one handler, and a new assignment replaces the old one. The handler receives an event object with target, currentTarget, preventDefault, and stopPropagation, and in a regular function this is the element.

Full answer

An event is a signal that something happened: a click, a key press, a form submit, or a page load. You react by registering a handler (a callback).

Three ways to register: an HTML attribute (<button onclick="run()">, which mixes markup and code and is best avoided), a property (button.onclick = fn), and button.addEventListener('click', fn). The property form allows only one handler per event type, and assigning again replaces it. addEventListener allows many listeners and gives options: { once: true } removes the listener after the first call, { passive: true } promises not to call preventDefault (useful for scroll and touch performance), and { capture: true } listens during the capture phase. To remove a listener, call removeEventListener with the same type and the same function reference, so anonymous functions cannot be removed.

The event object: event.type, event.target (the element that triggered the event), event.currentTarget (the element the listener is attached to), event.preventDefault() (stops the default action, such as a form submit or a link navigation), event.stopPropagation() (stops the event from moving to other elements), and for keyboard and mouse events, properties such as key, clientX, and shiftKey.

this and handlers: in a regular function handler, this is the element (the same as currentTarget). In an arrow function, this is taken from the surrounding scope, so use event.currentTarget there. Passing obj.method loses the object as this.

Other basics:

  • A handler may be an object with a handleEvent method.
  • Events fire in the order of registration for the same element and phase.
  • Custom events: element.dispatchEvent(new CustomEvent('name', { detail })).
  • submit events happen on the form, not the button, and preventDefault stops the page reload.
  • Remove listeners for elements that live long or that you re-create, to avoid leaks.
javascript
document.body.innerHTML = '<button id="btn">Click</button><form id="form"><input name="q" value="js"><button type="submit">Go</button></form>';
const button = document.getElementById('btn');
const log = [];

button.onclick = () => log.push('onclick A');
button.onclick = () => log.push('onclick B (replaced A)');
button.addEventListener('click', () => log.push('listener 1'));
button.addEventListener('click', () => log.push('listener 2'));
button.addEventListener('click', () => log.push('once only'), { once: true });
button.click();
button.click();
console.log(log);

// removing needs the same reference
const named = () => log.push('named handler');
button.addEventListener('click', named);
button.removeEventListener('click', named);
button.removeEventListener('click', () => {}); // a different function: nothing removed
log.length = 0;
button.click();
console.log(log);

// the event object and this
button.addEventListener('click', function (event) {
  console.log('regular function: this === currentTarget:', this === event.currentTarget, '| type:', event.type, '| target id:', event.target.id);
});
button.addEventListener('click', (event) => {
  console.log('arrow function: this is not the button:', this !== button, '| use event.currentTarget:', event.currentTarget.id);
});
button.click();

// preventDefault on a form submit
const form = document.getElementById('form');
form.addEventListener('submit', (event) => {
  event.preventDefault();
  console.log('submitted with value', new FormData(form).get('q'), '| defaultPrevented:', event.defaultPrevented);
});
form.requestSubmit();

// custom events
const box = document.createElement('div');
box.addEventListener('greet', (event) => console.log('custom event detail:', event.detail));
box.dispatchEvent(new CustomEvent('greet', { detail: { who: 'Asha' } }));

// handler objects
const handlerObject = { count: 0, handleEvent(event) { this.count++; console.log('handleEvent called, count', this.count, event.type); } };
button.addEventListener('click', handlerObject);
button.click();

Written for a browser console or script tag; checked here with Node.js v24.22.1 and jsdom, two runs with identical output. Output: [ 'onclick B (replaced A)', 'listener 1', 'listener 2', 'once only', 'onclick B (replaced A)', 'listener 1', 'listener 2' ] [ 'onclick B (replaced A)', 'listener 1', 'listener 2' ] regular function: this === currentTarget: true | type: click | target id: btn arrow function: this is not the button: true | use event.currentTarget: btn submitted with value js | defaultPrevented: true custom event detail: { who: 'Asha' } regular function: this === currentTarget: true | type: click | target id: btn arrow function: this is not the button: true | use event.currentTarget: btn handleEvent called, count 1 click

Key points

  • addEventListener allows many handlers and options (once, passive, capture); onclick keeps only one.
  • Remove a listener with the same function reference; anonymous functions cannot be removed.
  • Event object: target, currentTarget, preventDefault, stopPropagation, plus key and mouse details.
  • In a regular function this is the element; arrow functions need event.currentTarget.
  • Use submit on the form with preventDefault; clean up listeners you no longer need.

Common mistakes

  • Assigning onclick twice and losing the first handler.
  • Trying to remove an anonymous listener.
  • Using this inside an arrow function handler and expecting the element.
  • Listening for click on a submit button instead of submit on the form.

Follow-ups

  • What is the difference between target and currentTarget?
  • When would you use the passive option?
  • How does event delegation reduce the number of listeners?

Tips

  • State the main difference: one handler against many.
  • Mention the same-reference rule for removal.
  • Explain this in regular and arrow handlers.