Event Listeners0%

Event Listeners

Beginner12 min read•Updated: Jul 11, 2026
Study Materials

Event Listeners in Modern JavaScript

User interaction in web applications is powered by the JavaScript event system. Event listeners observe events dispatched by the browser (clicks, keypresses, network states, form submissions) and execute designated callback functions in response.


1. The addEventListener Architecture

The standard method for attaching handlers is EventTarget.prototype.addEventListener():

Output
┌──────────────┐ Event (e.g. 'click') ┌────────────────────┐
│ DOM Node │ ───────────────────────────────────► │ Listener Callback │
│ (Button/Form)│ ◄─────────────────────────────────── │ (event) => { } │
└──────────────┘ └────────────────────┘
JavaScript
const saveBtn = document.querySelector('#btn-save');
 
function handleSave(event) {
console.log('Button clicked at coordinates:', event.clientX, event.clientY);
}
 
saveBtn.addEventListener('click', handleSave);

Why avoid inline HTML handlers?

HTML
<!-- AVOID: Breaks Content Security Policy (CSP), mixes markup with logic -->
<button onclick="handleSave()">Save</button>

addEventListener() allows multiple listeners for the same event type, supports passive options, and maintains a strict separation of presentation and logic.


2. The Event Object: type, target, and currentTarget

Whenever an event triggers, the browser automatically passes an Event object to the callback:

JavaScript
button.addEventListener('click', (e) => {
console.log('Event Type:', e.type); // 'click'
console.log('Origin Element (target):', e.target); // Deepest element that was clicked
console.log('Bound Element (currentTarget):', e.currentTarget); // Element hosting this listener
console.log('Timestamp:', e.timeStamp);
});

target vs. currentTarget

  • event.target: The exact element that initiated the event (e.g., an <i> icon inside a <button>).
  • event.currentTarget: The element to which the event listener is currently attached (the <button>).

3. Removing Event Listeners with removeEventListener()

To remove an event listener, you must supply the identical function reference. Anonymous inline arrow functions cannot be removed!

JavaScript
function onWindowResize() {
console.log('Current window width:', window.innerWidth);
}
 
// Attach listener
window.addEventListener('resize', onWindowResize);
 
// Detach listener later (e.g., when component unmounts)
window.removeEventListener('resize', onWindowResize);
 
// CAUTION: This CANNOT be removed!
window.addEventListener('resize', () => console.log('Resized'));
// window.removeEventListener('resize', () => console.log('Resized')); // FAILS: Different memory reference!

4. Advanced Event Options: once, passive, and capture

addEventListener accepts a third argument—either a boolean (for capture) or an options object:

JavaScript
button.addEventListener('click', () => {
console.log('This will only run once!');
}, { once: true }); // Automatically detaches after firing once
 
// Performance optimization for scroll/touch events
window.addEventListener('scroll', handleScroll, {
passive: true // Informs browser that preventDefault() will NEVER be called, preventing UI lag
});

5. AbortController: Modern Event Cleanup

ES2022 introduced signal-based event cancellation using AbortController. This allows you to remove dozens of event listeners simultaneously with a single command:

JavaScript
const controller = new AbortController();
const { signal } = controller;
 
const btn1 = document.querySelector('#b1');
const btn2 = document.querySelector('#b2');
 
btn1.addEventListener('click', () => console.log('Btn 1 clicked'), { signal });
btn2.addEventListener('click', () => console.log('Btn 2 clicked'), { signal });
 
// Later, cancel ALL listeners attached with this signal
controller.abort();

Interactive Quiz

Practice Quiz

Question 1
Why can an anonymous arrow function listener NOT be removed via removeEventListener()?
Question 2
What is the difference between event.target and event.currentTarget?
Question 3
What listener option ensures that an event handler fires only a single time and then auto-detaches?
Question 4
What does setting { passive: true } achieve on touch and scroll event listeners?
Question 5
Which modern JavaScript API allows removing multiple event listeners across various elements using a single signal?
Next Lesson

Event Bubbling & Capturing

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

PrevNext