MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Event Listeners0%
Study Materials
JavaScript for IntermediateProgress 0%
1.1Block Scope with let & const1.2Template Literals1.3Destructuring Arrays and Objects1.4Default Parameters1.5Enhanced Object Literals
4.1Event Listeners4.2Event Bubbling & Capturing4.3Keyboard & Mouse Events4.4Form Events and Validation
HomeTutorialsJavaScript for IntermediateEvent Listeners
Event Bubbling & Capturing

Event Listeners

Beginner12 min read•Updated: 2026-09-15•By Er. Sumit Kumar (MSK Institute)
Study Materials

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():

1┌──────────────┐ Event (e.g. 'click') ┌────────────────────┐
2│ DOM Node │ ───────────────────────────────────► │ Listener Callback │
3│ (Button/Form)│ ◄─────────────────────────────────── │ (event) => { } │
4└──────────────┘ └────────────────────┘

Why avoid inline HTML handlers?

1<!-- AVOID: Breaks Content Security Policy (CSP), mixes markup with logic -->
2<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:

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

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!

1function onWindowResize() {
2 console.log('Current window width:', window.innerWidth);
3}
4 
5// Attach listener
6window.addEventListener('resize', onWindowResize);
7 
8// Detach listener later (e.g., when component unmounts)
9window.removeEventListener('resize', onWindowResize);
10 
11// CAUTION: This CANNOT be removed!
12window.addEventListener('resize', () => console.log('Resized'));
13// 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:

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

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:

1const controller = new AbortController();
2const { signal } = controller;
3 
4const btn1 = document.querySelector('#b1');
5const btn2 = document.querySelector('#b2');
6 
7btn1.addEventListener('click', () => console.log('Btn 1 clicked'), { signal });
8btn2.addEventListener('click', () => console.log('Btn 2 clicked'), { signal });
9 
10// Later, cancel ALL listeners attached with this signal
11controller.abort();

Interactive Quiz• Knowledge Check

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

Previous LessonNext Lesson
Styling with classListEvent Bubbling & Capturing

Practice Quiz

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

Mentor-Led Practical Training

Master JavaScript for Intermediate with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext