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
Custom Events & Event Dispatching0%
Study Materials
JavaScript for AdvancedProgress 0%
1.1Higher-Order Functions & Currying1.2Function Composition & Pipelining1.3Memoization & Pure Functions1.4Execution Context & Call Stack Deep Dive1.5Scope Chain & Lexical Environment
8.1Custom Events & Event Dispatching8.2Debouncing vs Throttling Deep Dive8.3Passive Event Listeners & Touch Optimization8.4Pointer Events & Gesture Handling
HomeTutorialsJavaScript for AdvancedCustom Events & Event Dispatching
Debouncing vs Throttling Deep Dive

Custom Events & Event Dispatching

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

While standard DOM events (click, input, keydown) handle direct user input, modular architectures require components to communicate domain-specific events—such as cart:item-added, modal:closed, or user:authenticated. The CustomEvent API allows you to create, dispatch, and intercept custom events across the DOM and Web Components.


1. Creating and Dispatching a CustomEvent

A CustomEvent takes an event type string and an optional initialization dictionary:

1// Step 1: Instantiate the Custom Event
2const itemAddedEvent = new CustomEvent('cart:item-added', {
3 detail: {
4 productId: 'SKU-9921',
5 name: 'Ergonomic Keyboard',
6 price: 129.99,
7 timestamp: Date.now()
8 },
9 bubbles: true, // Allows event to bubble up through parent DOM ancestors
10 composed: true, // CRITICAL: Allows event to cross Shadow DOM boundaries!
11 cancelable: true // Allows listeners to call event.preventDefault()
12});
13 
14// Step 2: Dispatch from any DOM element or window
15const cartButton = document.querySelector('#btn-add-to-cart');
16cartButton.dispatchEvent(itemAddedEvent);

2. Listening to Custom Events & Accessing detail

Event payloads passed in { detail } are available on event.detail:

1// Listener attached to ancestor or window
2window.addEventListener('cart:item-added', (event) => {
3 console.log('Item Added Event Intercepted!');
4 console.log('Product Name:', event.detail.name);
5 console.log('Price:', event.detail.price);
6 
7 // Update navigation badge
8 updateNavCartBadge();
9});

3. Crossing the Shadow DOM: composed: true

By default, events dispatched inside a Shadow DOM are trapped inside and cannot bubble up into the main document. Setting composed: true allows the event to penetrate through the shadow boundary into the outer Light DOM:

1 Inside Shadow DOM:
2 button.dispatchEvent(new CustomEvent('user-action', {
3 bubbles: true,
4 composed: true <── Crosses #shadow-root!
5 }))
6 │
7 ▼
8 Main Document receives event: window.addEventListener('user-action')

4. Making Custom Events Cancelable

If you set cancelable: true, listeners can call event.preventDefault(). The caller of dispatchEvent() receives a boolean indicating whether the action was permitted:

1// Component dispatching event:
2function requestDeleteFile(fileName) {
3 const event = new CustomEvent('file:before-delete', {
4 detail: { fileName },
5 cancelable: true
6 });
7 
8 // dispatchEvent returns FALSE if any listener called preventDefault()!
9 const isAllowed = window.dispatchEvent(event);
10 
11 if (isAllowed) {
12 console.log(`Proceeding with deletion of: ${fileName}`);
13 deleteFile(fileName);
14 } else {
15 console.warn(`Deletion of ${fileName} was cancelled by an event listener.`);
16 }
17}
18 
19// Security guard listener canceling deletion:
20window.addEventListener('file:before-delete', (e) => {
21 if (e.detail.fileName.endsWith('.protected')) {
22 e.preventDefault(); // Cancel deletion!
23 alert('Cannot delete protected system files!');
24 }
25});

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What property of a CustomEvent holds the arbitrary payload data passed to it?
Question 2
What option must be set to true on a CustomEvent so it can bubble out of a Shadow DOM into the main Light DOM?
Question 3
What does element.dispatchEvent(event) return if a listener calls event.preventDefault() on a cancelable event?
Question 4
Can custom events bubble up through ancestor elements like standard click events?
Question 5
What is the primary architectural benefit of using Custom Events for component communication?
Next Lesson

Debouncing vs Throttling Deep Dive

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

Related Lessons

Previous LessonNext Lesson
Storage Quotas & Persistence PoliciesDebouncing vs Throttling Deep Dive

Practice Quiz

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

Mentor-Led Practical Training

Master JavaScript for Advanced 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