JavaScript and TypeScript course Β· Module 8: Events and the DOM

Event Propagation (Event Bubbling)

9 min read Β·
In this lesson7

"Look," Ray Arnold leads you to the central alarm panel of Jurassic Park. "When a sensor detects a threat in enclosure 7-B, the signal doesn't stop there. It goes higher - to the sector system, then to the main control center, and finally to the central alarm. This is called signal propagation."

Ray shows the alarm system diagram. "In the DOM, it works exactly the same way. When you click an element, the event 'bubbles' up through the entire DOM tree - from the target element, through its parents, all the way to the document itself."

What Is Event Bubbling?

Event bubbling is a fundamental mechanism in JavaScript where events propagate from the element on which they occurred, upward through all its ancestors in the DOM tree.

Three Phases of Event Propagation

"Most events," Ray explains, "go through three phases. It's like a security protocol - we check everything in a specific order." Some events, such as focus, blur, mouseenter and mouseleave, do not bubble: they go through the capture phase and reach the target, but do not travel back up. The bubbling counterparts of focus and blur are focusin and focusout.

// Event phases:
// 1. CAPTURE (capturing) - from document down to the target element
// 2. TARGET (target) - on the target element itself
// 3. BUBBLE (bubbling) - from the target element up to document

document.addEventListener('click', function(event) {
  // eventPhase shows the current phase:
  // 1 = CAPTURING_PHASE
  // 2 = AT_TARGET
  // 3 = BUBBLING_PHASE
  console.log('Event phase:', event.eventPhase);
}, true); // true = listen in capture phase

Practical Propagation Example

"Let's see it in action," says Ray, opening the dinosaur enclosure structure in the system.

// HTML structure:
// <div id="park-zone" class="zone">
//   <div id="sector-b" class="sector">
//     <div id="enclosure-7" class="enclosure">
//       <button id="emergency-btn" class="button">ALARM</button>
//     </div>
//   </div>
// </div>

const parkZone = document.getElementById('park-zone');
const sectorB = document.getElementById('sector-b');
const enclosure7 = document.getElementById('enclosure-7');
const emergencyBtn = document.getElementById('emergency-btn');

// Listener on the button (most nested)
emergencyBtn.addEventListener('click', function(event) {
  console.log('1. ALARM! Emergency button pressed');
  console.log('   Target:', event.target.id);
  console.log('   CurrentTarget:', event.currentTarget.id);
  console.log('   Phase:', event.eventPhase); // 2 (AT_TARGET)

  activateLocalAlarm();
});

// Listener on the enclosure
enclosure7.addEventListener('click', function(event) {
  console.log('2. Enclosure 7 - alarm activation detected');
  console.log('   Target:', event.target.id); // emergency-btn
  console.log('   CurrentTarget:', event.currentTarget.id); // enclosure-7
  console.log('   Phase:', event.eventPhase); // 3 (BUBBLING_PHASE)

  closeEnclosureGates();
});

// Listener on the sector
sectorB.addEventListener('click', function(event) {
  console.log('3. Sector B - alarm propagated to sector');
  console.log('   Target:', event.target.id); // emergency-btn
  console.log('   CurrentTarget:', event.currentTarget.id); // sector-b
  console.log('   Phase:', event.eventPhase); // 3 (BUBBLING_PHASE)

  lockSectorGates();
});

// Listener on the entire park zone
parkZone.addEventListener('click', function(event) {
  console.log('4. Park Zone - alarm reached central control');
  console.log('   Target:', event.target.id); // emergency-btn
  console.log('   CurrentTarget:', event.currentTarget.id); // park-zone
  console.log('   Phase:', event.eventPhase); // 3 (BUBBLING_PHASE)

  notifyCentralControl();
});

// Listener on the entire document
document.addEventListener('click', function(event) {
  console.log('5. DOCUMENT - highest level of the system notified');
  console.log('   The event reached the very top of the hierarchy');

  logSystemEvent(event);
});

function activateLocalAlarm() {
  console.log('   β†’ Activating local alarm in enclosure 7');
}

function closeEnclosureGates() {
  console.log('   β†’ Closing enclosure 7 gates');
}

function lockSectorGates() {
  console.log('   β†’ Locking all gates in sector B');
}

function notifyCentralControl() {
  console.log('   β†’ Notifying central control center');
}

function logSystemEvent(event) {
  console.log('   β†’ Logging event in the main system');
}

// After clicking the button, we'll see all 5 messages in order!

stopPropagation() - Stopping Propagation

"Sometimes," Ray presses a red button, "we want to stop propagation. Like a safety valve that isolates the problem locally."

Controlled Stopping

const button = document.getElementById('local-action-btn');
const container = document.getElementById('action-container');
const section = document.getElementById('main-section');

button.addEventListener('click', function(event) {
  console.log('1. Button clicked');
  performLocalAction();

  // STOP propagation - the event won't go higher
  event.stopPropagation();
  console.log('   Propagation stopped - the event won\'t reach parents');
});

container.addEventListener('click', function(event) {
  console.log('2. This listener WON\'T EXECUTE (due to stopPropagation)');
  performContainerAction();
});

section.addEventListener('click', function(event) {
  console.log('3. This listener also WON\'T EXECUTE');
  performSectionAction();
});

// After clicking the button, we'll only see message "1."

Practical Use Case - Modal Window

"The most common case," Ray explains, "is closing modal windows."

// Modal that closes when clicking the background (overlay)
const modal = document.getElementById('dino-info-modal');
const modalContent = document.getElementById('modal-content');
const closeButton = document.getElementById('modal-close');

// Clicking the background (overlay) closes the modal
modal.addEventListener('click', function(event) {
  console.log('Background clicked - closing modal');
  closeModal();
});

// Clicking the modal content does NOT close it
modalContent.addEventListener('click', function(event) {
  event.stopPropagation(); // IMPORTANT! Stop propagation to overlay
  console.log('Content clicked - modal stays open');
});

// Close button
closeButton.addEventListener('click', function(event) {
  event.stopPropagation(); // Optional, but safe
  console.log('Close button - closing modal');
  closeModal();
});

function closeModal() {
  modal.style.display = 'none';
  console.log('Modal closed');
}

function openModal(dinosaurId) {
  modal.style.display = 'block';
  loadDinosaurData(dinosaurId);
  console.log('Modal opened for dinosaur:', dinosaurId);
}

Capture Phase - The Capturing Phase

"Most developers," says Ray, "only use the bubble phase. But sometimes we need the capture phase - checking everything BEFORE it reaches the target."

Listening in the Capture Phase

const outer = document.getElementById('outer');
const middle = document.getElementById('middle');
const inner = document.getElementById('inner');

// Bubble phase (default, capture: false)
outer.addEventListener('click', function(event) {
  console.log('BUBBLE: Outer');
});

middle.addEventListener('click', function(event) {
  console.log('BUBBLE: Middle');
});

inner.addEventListener('click', function(event) {
  console.log('BUBBLE: Inner (target)');
});

// Capture phase (capture: true)
outer.addEventListener('click', function(event) {
  console.log('CAPTURE: Outer');
}, true); // true enables capture phase

middle.addEventListener('click', function(event) {
  console.log('CAPTURE: Middle');
}, true);

inner.addEventListener('click', function(event) {
  console.log('CAPTURE: Inner (target)');
}, true);

// After clicking inner, we'll see:
// CAPTURE: Outer (going down)
// CAPTURE: Middle (going down)
// CAPTURE: Inner (target) (target)
// BUBBLE: Inner (target) (target)
// BUBBLE: Middle (going up)
// BUBBLE: Outer (going up)

Practical Use of Capture - Global Interception

// Global handler for all clicks (e.g., for analytics)
document.addEventListener('click', function(event) {
  const targetElement = event.target;

  console.log('=== GLOBAL CLICK TRACKER ===');
  console.log('Element:', targetElement.tagName);
  console.log('ID:', targetElement.id);
  console.log('Classes:', targetElement.className);
  console.log('Position:', event.clientX, event.clientY);
  console.log('Time:', new Date().toISOString());

  // Send to analytics system
  trackClickEvent({
    element: targetElement.tagName,
    elementId: targetElement.id,
    elementClass: targetElement.className,
    timestamp: Date.now(),
    position: { x: event.clientX, y: event.clientY }
  });
}, true); // Capture - executes BEFORE all other handlers

function trackClickEvent(data) {
  console.log('Sending analytics data:', data);
  // Send to analytics server
}

stopImmediatePropagation() - Immediate Stop

"This is a more drastic measure," Ray warns. "It stops NOT ONLY propagation to parents, but also all remaining listeners on the same element."

const criticalButton = document.getElementById('critical-system-btn');

// First listener
criticalButton.addEventListener('click', function(event) {
  console.log('1. First listener - executes');

  const systemStatus = checkSystemStatus();

  if (systemStatus === 'CRITICAL') {
    console.log('   SYSTEM CRITICAL - stopping all remaining actions!');
    event.stopImmediatePropagation(); // STOP EVERYTHING!
    handleCriticalSituation();
    return;
  }
});

// Second listener - WON'T execute if stopImmediatePropagation was called
criticalButton.addEventListener('click', function(event) {
  console.log('2. Second listener - normal flow');
  performNormalAction();
});

// Third listener - WON'T execute if stopImmediatePropagation was called
criticalButton.addEventListener('click', function(event) {
  console.log('3. Third listener - logging');
  logAction();
});

function checkSystemStatus() {
  // Simulation of system status check
  const random = Math.random();
  return random > 0.7 ? 'CRITICAL' : 'NORMAL';
}

function handleCriticalSituation() {
  console.log('   β†’ Activating emergency protocols');
  console.log('   β†’ Locking all systems');
  console.log('   β†’ Notifying administration');
}

Practical Notification System

"Let's see how to use propagation in a real system," says Ray, opening the park notification system code.

class ParkNotificationSystem {
  constructor() {
    this.notifications = [];
    this.setupGlobalListeners();
  }

  setupGlobalListeners() {
    // Global listener in capture phase
    document.addEventListener('click', (e) => {
      this.trackInteraction(e);
    }, true);

    // Listener for all notifications
    const notificationContainer = document.getElementById('notifications');

    if (notificationContainer) {
      notificationContainer.addEventListener('click', (e) => {
        this.handleNotificationClick(e);
      });
    }
  }

  trackInteraction(event) {
    const target = event.target;

    // Track only key interactions
    if (target.matches('.trackable')) {
      console.log('Interaction with trackable element:', target.id);

      this.logInteraction({
        element: target.id,
        type: event.type,
        timestamp: Date.now()
      });
    }
  }

  handleNotificationClick(event) {
    const notification = event.target.closest('.notification');

    if (!notification) return;

    // Stop propagation - we don't want the notification click
    // to trigger other handlers
    event.stopPropagation();

    const notificationId = notification.dataset.id;
    const action = event.target.dataset.action;

    console.log(`Notification clicked: ${notificationId}`);
    console.log(`Action: ${action}`);

    switch(action) {
      case 'dismiss':
        this.dismissNotification(notificationId);
        break;

      case 'view':
        this.viewNotification(notificationId);
        break;

      case 'action':
        this.performNotificationAction(notificationId);
        break;

      default:
        console.log('Clicked somewhere in the notification - showing details');
        this.showNotificationDetails(notificationId);
    }
  }

  dismissNotification(id) {
    console.log(`Closing notification: ${id}`);
    const notification = document.querySelector(`[data-id="${id}"]`);

    if (notification) {
      notification.classList.add('dismissing');

      setTimeout(() => {
        notification.remove();
        this.notifications = this.notifications.filter(n => n.id !== id);
        console.log(`Notification ${id} removed`);
      }, 300);
    }
  }

  viewNotification(id) {
    console.log(`Displaying notification details: ${id}`);
    // Details display logic
  }

  performNotificationAction(id) {
    const notification = this.notifications.find(n => n.id === id);

    if (notification && notification.actionCallback) {
      console.log(`Executing action for notification: ${id}`);
      notification.actionCallback();
    }
  }

  showNotificationDetails(id) {
    console.log(`Showing full notification details: ${id}`);
    // Full details display logic
  }

  logInteraction(data) {
    console.log('Logging interaction:', data);
    // Save to analytics system
  }

  createNotification(message, type = 'info', actionCallback = null) {
    const id = 'notif-' + Date.now();

    const notification = {
      id,
      message,
      type,
      actionCallback,
      timestamp: new Date()
    };

    this.notifications.push(notification);
    this.renderNotification(notification);

    console.log('New notification created:', id);
    return id;
  }

  renderNotification(notification) {
    const container = document.getElementById('notifications');

    const notifElement = document.createElement('div');
    notifElement.className = `notification notification-${notification.type}`;
    notifElement.dataset.id = notification.id;

    notifElement.innerHTML = `
      <div class="notification-content">
        <p>${notification.message}</p>
        <small>${notification.timestamp.toLocaleTimeString()}</small>
      </div>
      <div class="notification-actions">
        ${notification.actionCallback ? '<button data-action="action">Action</button>' : ''}
        <button data-action="dismiss">Close</button>
      </div>
    `;

    container.appendChild(notifElement);
  }
}

// System initialization
const parkNotifications = new ParkNotificationSystem();

// Example usage
parkNotifications.createNotification(
  'Unusual activity detected in the T-Rex enclosure',
  'warning',
  () => {
    console.log('Action: Opening T-Rex monitoring panel');
    openTrexMonitoring();
  }
);

Summary

"Event propagation," Ray summarizes, "is a powerful mechanism. Just as in the park's alarm systems, where a signal propagates to the appropriate levels, events in JavaScript flow through the DOM tree. Understanding this mechanism is crucial for effective event handling."

Key concepts:

  • Most events "bubble" from the target element up to document and window (focus, blur, mouseenter and mouseleave do not)
  • Three phases: Capture β†’ Target β†’ Bubble
  • event.stopPropagation() stops propagation to parents
  • event.stopImmediatePropagation() stops all remaining listeners
  • Capture phase (third parameter true) executes before bubble
  • event.target vs event.currentTarget - crucial difference during propagation
Code for this lesson: index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dinosaur Modal - Jurassic Park</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
            margin: 0;
            padding: 20px;
            color: white;
        }

        .main-container {
            max-width: 800px;
            margin: 0 auto;
        }

        h1 {
            text-align: center;
            margin-bottom: 30px;
        }

        .dino-buttons {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .dino-button {
            background: linear-gradient(45deg, #3498db, #2980b9);
            color: white;
            border: none;
            border-radius: 10px;
            padding: 20px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 16px;
            font-weight: bold;
        }

        .dino-button:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(52, 152, 219, 0.4);
        }

        .dino-emoji {
            font-size: 48px;
            display: block;
            margin-bottom: 10px;
        }

        /* Styles for the modal */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            backdrop-filter: blur(5px);
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .modal.show {
            opacity: 1;
        }

        .modal-content {
            background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
            margin: 5% auto;
            padding: 0;
            border-radius: 15px;
            width: 90%;
            max-width: 600px;
            max-height: 80vh;
            overflow-y: auto;
            transform: scale(0.7);
            transition: transform 0.3s ease;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
        }

        .modal.show .modal-content {
            transform: scale(1);
        }

        .modal-header {
            background: linear-gradient(45deg, #e74c3c, #c0392b);
            padding: 20px;
            color: white;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-header h2 {
            margin: 0;
            font-size: 24px;
        }

        .close-btn {
            background: none;
            border: none;
            color: white;
            font-size: 24px;
            cursor: pointer;
            padding: 0;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }

        .close-btn:hover {
            background: rgba(255, 255, 255, 0.2);
            transform: rotate(90deg);
        }

        .modal-body {
            padding: 30px;
            color: white;
            line-height: 1.6;
        }

        .dino-image {
            width: 100%;
            max-width: 300px;
            height: 200px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 10px;
            margin: 20px auto;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 80px;
        }

        .dino-stats {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            margin: 20px 0;
        }

        .stat-item {
            background: rgba(255, 255, 255, 0.1);
            padding: 15px;
            border-radius: 8px;
            text-align: center;
        }

        .stat-label {
            color: #bdc3c7;
            font-size: 14px;
            margin-bottom: 5px;
        }

        .stat-value {
            font-size: 18px;
            font-weight: bold;
            color: #ecf0f1;
        }

        .modal-footer {
            padding: 20px 30px;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
            display: flex;
            gap: 15px;
            justify-content: center;
        }

        .action-btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-weight: bold;
            transition: all 0.3s ease;
        }

        .book-tour-btn {
            background: #27ae60;
            color: white;
        }

        .book-tour-btn:hover {
            background: #2ecc71;
        }

        .add-favorite-btn {
            background: #f39c12;
            color: white;
        }

        .add-favorite-btn:hover {
            background: #e67e22;
        }

        .instructions {
            background: rgba(52, 152, 219, 0.2);
            border: 1px solid #3498db;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 30px;
        }

        .key-hint {
            font-size: 14px;
            color: #bdc3c7;
            text-align: center;
            margin-top: 20px;
        }

        .key-hint kbd {
            background: rgba(255, 255, 255, 0.2);
            padding: 2px 8px;
            border-radius: 4px;
            font-family: monospace;
        }
    </style>
</head>
<body>
    <div class="main-container">
        <h1>Dinosaur Information</h1>

        <div class="instructions">
            Click on a dinosaur button to see detailed information in a modal window.
            <div class="key-hint">
                You can close the modal by clicking <kbd>Γ—</kbd>, clicking outside the window, or pressing <kbd>Escape</kbd>
            </div>
        </div>

        <div class="dino-buttons">
            <button class="dino-button" data-dino="trex">
                <span class="dino-emoji">β—†</span>
                Tyrannosaurus Rex
            </button>

            <button class="dino-button" data-dino="velociraptor">
                <span class="dino-emoji">β—†</span>
                Velociraptor
            </button>

            <button class="dino-button" data-dino="triceratops">
                <span class="dino-emoji">β—†</span>
                Triceratops
            </button>

            <button class="dino-button" data-dino="brachiosaurus">
                <span class="dino-emoji">β—†</span>
                Brachiosaurus
            </button>
        </div>
    </div>

    <!-- Modal (initially hidden) -->
    <div id="dinosaur-modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="modal-title">Dinosaur information</h2>
                <button class="close-btn" id="close-modal">&times;</button>
            </div>
            <div class="modal-body">
                <div id="dino-image" class="dino-image">β—†</div>

                <div id="dino-description">
                    Dinosaur description will be loaded here...
                </div>

                <div class="dino-stats">
                    <div class="stat-item">
                        <div class="stat-label">Geological era</div>
                        <div class="stat-value" id="era-value">-</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-label">Diet</div>
                        <div class="stat-value" id="diet-value">-</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-label">Length</div>
                        <div class="stat-value" id="length-value">-</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-label">Weight</div>
                        <div class="stat-value" id="weight-value">-</div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="action-btn book-tour-btn" id="book-tour">
                    Book a tour
                </button>
                <button class="action-btn add-favorite-btn" id="add-favorite">
                    Add to favorites
                </button>
            </div>
        </div>
    </div>

    <script>
        // Dinosaur data
        const dinosaurData = {
            trex: {
                name: "Tyrannosaurus Rex",
                emoji: "",
                era: "Late Cretaceous",
                diet: "Carnivore",
                length: "12-13 m",
                weight: "8-9 tons",
                description: "Tyrannosaurus Rex, known as \"King of tyrant lizards\", was one of the largest land predators of all time. Its powerful jaws could exert a force of up to 12,800 pounds per square inch. T-Rex lived approximately 68-66 million years ago in what is now North America."
            },
            velociraptor: {
                name: "Velociraptor",
                emoji: "",
                era: "Late Cretaceous",
                diet: "Carnivore",
                length: "2 m",
                weight: "15-20 kg",
                description: "Velociraptor was an intelligent, fast pack-hunting predator. Its name means \"swift hunter\". It was characterized by sickle-shaped claws on its hind legs, which were used to deliver lethal wounds to prey. It lived approximately 75-71 million years ago in Asia."
            },
            triceratops: {
                name: "Triceratops",
                emoji: "",
                era: "Late Cretaceous",
                diet: "Herbivore",
                length: "8-9 m",
                weight: "6-12 tons",
                description: "Triceratops was one of the last dinosaurs before the great extinction. Its characteristic three horns and bony frill served for defense against predators and for rivalry with other members of the species. It lived about 68-66 million years ago in North America."
            },
            brachiosaurus: {
                name: "Brachiosaurus",
                emoji: "",
                era: "Late Jurassic",
                diet: "Herbivore",
                length: "20-23 m",
                weight: "35-40 tons",
                description: "Brachiosaurus was one of the largest dinosaurs that ever walked the Earth. Its long neck allowed it to reach the tops of the tallest trees. Unlike other sauropods, its front legs were longer than its hind legs. It lived about 156-145 million years ago."
            }
        };

        // Get references to elements
        const modal = document.getElementById('dinosaur-modal');
        const closeBtn = document.getElementById('close-modal');
        const modalTitle = document.getElementById('modal-title');
        const dinoImage = document.getElementById('dino-image');
        const dinoDescription = document.getElementById('dino-description');
        const eraValue = document.getElementById('era-value');
        const dietValue = document.getElementById('diet-value');
        const lengthValue = document.getElementById('length-value');
        const weightValue = document.getElementById('weight-value');
        const bookTourBtn = document.getElementById('book-tour');
        const addFavoriteBtn = document.getElementById('add-favorite');

        // Function that opens the modal
        function openModal(dinoType) {
            const dino = dinosaurData[dinoType];

            // Fill modal with dinosaur data
            modalTitle.textContent = dino.name;
            dinoImage.textContent = dino.emoji;
            dinoDescription.textContent = dino.description;
            eraValue.textContent = dino.era;
            dietValue.textContent = dino.diet;
            lengthValue.textContent = dino.length;
            weightValue.textContent = dino.weight;

            // Show modal with animation
            modal.style.display = 'block';
            requestAnimationFrame(() => {
                modal.classList.add('show');
            });

            // Blocking scrolling on the body
            document.body.style.overflow = 'hidden';

            console.log(`Modal opened for: ${dino.name}`);
        }

        // Function that closes the modal
        function closeModal() {
            modal.classList.remove('show');

            setTimeout(() => {
                modal.style.display = 'none';
                document.body.style.overflow = 'auto';
            }, 300);

            console.log('Modal closed');
        }

        // Event listeners for dinosaur buttons
        document.querySelectorAll('.dino-button').forEach(button => {
            button.addEventListener('click', function() {
                const dinoType = this.dataset.dino;
                openModal(dinoType);
            });
        });

        // Event listener for the close button
        closeBtn.addEventListener('click', closeModal);

        // Close modal when clicking outside content
        modal.addEventListener('click', function(event) {
            if (event.target === modal) {
                closeModal();
            }
        });

        // Handle Escape key
        document.addEventListener('keydown', function(event) {
            if (event.key === 'Escape' && modal.classList.contains('show')) {
                closeModal();
            }
        });

        // Event listeners for the modal actions
        bookTourBtn.addEventListener('click', function() {
            const dinoName = modalTitle.textContent;
            alert(`Tour to ${dinoName} has been booked for the nearest available date!\n\nDetails will be sent to your email.`);
            closeModal();
        });

        addFavoriteBtn.addEventListener('click', function() {
            const dinoName = modalTitle.textContent;

            if (this.textContent.includes('Added')) {
                this.textContent = 'Add to favorites';
                this.style.background = '#f39c12';
                alert(`Removed ${dinoName} from favorites.`);
            } else {
                this.textContent = 'Added to favorites';
                this.style.background = '#27ae60';
                alert(`${dinoName} has been added to your favorite dinosaurs!`);
            }
        });

        // Demo of opening the modal from code
        setTimeout(() => {
            console.log('Demo: The T-Rex modal opens automatically in 3 seconds...');
        }, 3000);

        // Optional: open modal automatically after 5 seconds
        // setTimeout(() => openModal('trex'), 5000);
    </script>
</body>
</html>

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is the process called when an event travels upward from the target element through its parents?

  2. 2. In which phase of the event flow does a listener with { capture: true } option operate?

Hands-on tasks in the game

  • Code editor

    The index.html file has a #open-modal button and a hidden modal dialog #dino-modal (style.css shows it only with the open class). Fill in the blanks in the script: ___BLANK1___ is the classList method that adds the open class when the button is clicked, ___BLANK2___ is the key press event listened to on the document, and ___BLANK3___ is the event.key value of the Escape key. The dialog should open on click and close when Escape is pressed, but not when another key is pressed.

  • Vertical ordering

    In what order does event flow occur in the DOM?

  • Vertical ordering

    Arrange the steps for stopping event propagation:

  1. QuestionQuiz: Event Propagation
  2. QuestionQuiz: Event capture
  3. Coding taskExercise: Modal Dialog
  4. Put in orderVertical Sort: Event Flow
  5. Put in orderVertical Sort: stopPropagation

Useful articles