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

Event Delegation

12 min read Β·
In this lesson8

"In Jurassic Park," Ray Arnold points to the central monitoring panel, "we don't install a separate alarm system for every dinosaur. That would be costly and inefficient. Instead, we have a central sector monitoring system that handles all enclosures in its area."

Ray opens the system diagram. "Event delegation works on the same principle. Instead of assigning hundreds of event listeners to individual elements, we assign one listener to their common parent. This parent 'delegates' handling to the appropriate elements."

What Is Event Delegation?

Event delegation is a technique that uses event propagation (bubbling) to handle events on many elements through a single listener assigned to their common ancestor. It's one of the most important and efficient techniques in JavaScript.

The Problem: Many Event Listeners

"Let's see the problem," says Ray, showing code in which every dinosaur card gets its own listener inside a forEach loop.

// INEFFICIENT - separate listener for each card
const dinosaurCards = document.querySelectorAll('.dinosaur-card');

console.log(`Assigning listeners to ${dinosaurCards.length} dinosaur cards`);

dinosaurCards.forEach((card, index) => {
  card.addEventListener('click', function() {
    const dinoId = this.dataset.dinoId;
    const dinoName = this.dataset.dinoName;

    console.log(`Dinosaur clicked: ${dinoName} (ID: ${dinoId})`);
    showDinosaurDetails(dinoId);
  });

  console.log(`Listener ${index + 1}/${dinosaurCards.length} added`);
});

// Problems with this approach:
// 1. If we have 100 cards = 100 listeners in memory
// 2. Dynamically added cards WON'T have listeners
// 3. Must manually remove listeners when removing cards
// 4. Higher memory usage and slower page

It works, but a hundred cards means a hundred listeners, and a card added later stays deaf, because the loop ran only once.

The Solution: Event Delegation

"Now watch," Ray shows the better solution: a single listener on the gallery works out by itself which card was clicked.

// EFFICIENT - one listener on the container
const dinosaurGallery = document.getElementById('dinosaur-gallery');

dinosaurGallery.addEventListener('click', function(event) {
  // Find the closest dinosaur card (even if a child of the card was clicked)
  const card = event.target.closest('.dinosaur-card');

  // If no dinosaur card was clicked, ignore
  if (!card) return;

  // Make sure the card is a child of our gallery
  if (!dinosaurGallery.contains(card)) return;

  const dinoId = card.dataset.dinoId;
  const dinoName = card.dataset.dinoName;

  console.log(`Dinosaur clicked: ${dinoName} (ID: ${dinoId})`);
  showDinosaurDetails(dinoId);
});

// Advantages of this approach:
// 1. Only ONE listener regardless of the number of cards
// 2. Automatically handles dynamically added cards
// 3. Better memory management
// 4. Easier code maintenance

A click on a card's image bubbles all the way up to the gallery: event.target is the element that was clicked, and event.currentTarget is the element with the listener, that is, the gallery. The closest() method walks up from target and returns the matching card or null, while contains() checks that the card lives inside the gallery. The whole technique comes down to four steps: find the container, add a listener to it, check event.target, and run the action for the matching element.

Practical Example - Dinosaur Card System

"Let's build a complete system," says Ray. Here is the card structure and the start of a listener that recognizes the details and feeding buttons.

// HTML structure:
// <div id="dino-gallery">
//   <div class="dinosaur-card" data-dino-id="1" data-dino-name="T-Rex">
//     <img src="trex.jpg" alt="T-Rex">
//     <h3>Tyrannosaurus Rex</h3>
//     <div class="card-actions">
//       <button class="view-btn">Details</button>
//       <button class="feed-btn">Feed</button>
//       <button class="favorite-btn">β˜…</button>
//     </div>
//   </div>
//   ... more cards
// </div>

const gallery = document.getElementById('dino-gallery');

gallery.addEventListener('click', function(event) {
  const target = event.target;

  // Handle details button
  if (target.classList.contains('view-btn')) {
    const card = target.closest('.dinosaur-card');
    const dinoId = card.dataset.dinoId;
    const dinoName = card.dataset.dinoName;

    console.log(`Opening details for: ${dinoName}`);
    openDinosaurModal(dinoId);
    return; // Stop further checking
  }

  // Handle feed button
  if (target.classList.contains('feed-btn')) {
    const card = target.closest('.dinosaur-card');
    const dinoId = card.dataset.dinoId;
    const dinoName = card.dataset.dinoName;

    console.log(`Starting feeding: ${dinoName}`);
    feedDinosaur(dinoId);
    return;
  }

We read the data-dino-id attribute as dataset.dinoId, because hyphens turn into camelCase. Every branch ends with return, so one click runs exactly one action. Next come favorites and the card itself.

  // Handle favorite button
  if (target.classList.contains('favorite-btn')) {
    const card = target.closest('.dinosaur-card');
    const dinoId = card.dataset.dinoId;
    const dinoName = card.dataset.dinoName;

    // Toggle favorite state
    target.classList.toggle('active');

    if (target.classList.contains('active')) {
      console.log(`Added to favorites: ${dinoName}`);
      addToFavorites(dinoId);
      target.textContent = 'β˜…';
    } else {
      console.log(`Removed from favorites: ${dinoName}`);
      removeFromFavorites(dinoId);
      target.textContent = 'β˜†';
    }
    return;
  }

  // Handle clicking the card itself (but not buttons)
  const card = target.closest('.dinosaur-card');
  if (card && gallery.contains(card)) {
    const dinoId = card.dataset.dinoId;
    const dinoName = card.dataset.dinoName;

    console.log(`Card clicked: ${dinoName}`);
    highlightCard(card);
  }
});

The card is checked last, otherwise a click on a button would highlight it along the way. A classList.contains check is enough here, because the buttons contain plain text. An icon inside would take over the click and the condition would fail. Finally, the helpers.

function openDinosaurModal(dinoId) {
  console.log(`Loading dinosaur data ID: ${dinoId}`);
  // Modal opening logic
}

function feedDinosaur(dinoId) {
  console.log(`Activating feeding system for dinosaur ID: ${dinoId}`);
  console.log('Checking security...');
  console.log('Opening dispenser...');
  console.log('Feeding completed');
}

function addToFavorites(dinoId) {
  const favorites = JSON.parse(localStorage.getItem('favoriteDinosaurs') || '[]');
  if (!favorites.includes(dinoId)) {
    favorites.push(dinoId);
    localStorage.setItem('favoriteDinosaurs', JSON.stringify(favorites));
    console.log('Saved to favorites');
  }
}

function removeFromFavorites(dinoId) {
  let favorites = JSON.parse(localStorage.getItem('favoriteDinosaurs') || '[]');
  favorites = favorites.filter(id => id !== dinoId);
  localStorage.setItem('favoriteDinosaurs', JSON.stringify(favorites));
  console.log('Removed from favorites');
}

function highlightCard(card) {
  // Remove highlight from other cards
  document.querySelectorAll('.dinosaur-card.highlighted').forEach(c => {
    c.classList.remove('highlighted');
  });

  // Add highlight to the clicked card
  card.classList.add('highlighted');
  console.log('Card highlighted');
}

The helpers know nothing about events. The || '[]' fallback saves the very first visit, when getItem() returns null.

Dynamically Adding Elements

"The greatest advantage of delegation," Ray adds new elements to the interface, "is automatic handling of dynamically added elements."

const gallery = document.getElementById('dino-gallery');

// Event delegation - works for all cards, even future ones
gallery.addEventListener('click', function(event) {
  const card = event.target.closest('.dinosaur-card');
  if (!card) return;

  const dinoName = card.dataset.dinoName;
  console.log(`Clicked: ${dinoName}`);
});

// Function to dynamically add new cards
function addNewDinosaur(dinosaur) {
  const newCard = document.createElement('div');
  newCard.className = 'dinosaur-card';
  newCard.dataset.dinoId = dinosaur.id;
  newCard.dataset.dinoName = dinosaur.name;

  newCard.innerHTML = `
    <img src="${dinosaur.image}" alt="${dinosaur.name}">
    <h3>${dinosaur.name}</h3>
    <p>${dinosaur.species}</p>
    <div class="card-actions">
      <button class="view-btn">Details</button>
      <button class="feed-btn">Feed</button>
      <button class="favorite-btn">β˜†</button>
    </div>
  `;

  gallery.appendChild(newCard);
  console.log(`New dinosaur added: ${dinosaur.name}`);

  // NO NEED to add event listeners!
  // Delegation automatically handles the new card!
}

// Example usage
setTimeout(() => {
  addNewDinosaur({
    id: '15',
    name: 'Spinosaurus',
    species: 'Spinosaurus aegyptiacus',
    image: 'spinosaurus.jpg'
  });

  // The new card already works with clicks!
}, 3000);

There isn't a single addEventListener in addNewDinosaur(), yet the Spinosaurus added after three seconds responds to clicks right away, because they bubble up to the listener that has been waiting on the gallery from the start.

Advanced Delegation - Filters and Conditions

"Sometimes," Ray explains, "we need more precise control." Every button on the panel says what it should do through data-action, and the listener hands out the tasks.

const parkDashboard = document.getElementById('park-dashboard');

parkDashboard.addEventListener('click', function(event) {
  const target = event.target;

  // Delegation with data-action attribute
  const action = target.dataset.action;

  if (action) {
    console.log(`Action: ${action}`);

    switch(action) {
      case 'open-gate':
        handleOpenGate(target);
        break;

      case 'close-gate':
        handleCloseGate(target);
        break;

      case 'start-feeding':
        handleStartFeeding(target);
        break;

      case 'emergency-protocol':
        handleEmergencyProtocol(target);
        break;

      case 'view-stats':
        handleViewStats(target);
        break;

      default:
        console.log('Unknown action:', action);
    }

    return;
  }

A new action means a new case, not a new listener. When the element has no action, the listener checks classes with the matches() method and tags through tagName, which returns the name in uppercase, hence 'A'.

  // Delegation with classes
  if (target.matches('.enclosure-zone')) {
    const enclosureId = target.dataset.enclosureId;
    console.log(`Enclosure zone clicked: ${enclosureId}`);
    showEnclosureDetails(enclosureId);
    return;
  }

  // Delegation with tags
  if (target.tagName === 'A' && target.classList.contains('internal-link')) {
    event.preventDefault();
    const href = target.getAttribute('href');
    console.log(`Internal navigation: ${href}`);
    navigateInternal(href);
    return;
  }
});

function handleOpenGate(button) {
  const gateId = button.dataset.gateId;
  const enclosureId = button.dataset.enclosureId;

  console.log(`Opening gate ${gateId} in enclosure ${enclosureId}`);
  console.log('Checking security status...');
  console.log('Gate opened');
}

function handleCloseGate(button) {
  const gateId = button.dataset.gateId;
  console.log(`Closing gate ${gateId}`);
  console.log('Gate closed and secured');
}

function handleStartFeeding(button) {
  const enclosureId = button.dataset.enclosureId;
  const feedType = button.dataset.feedType;

  console.log(`Starting feeding in enclosure ${enclosureId}`);
  console.log(`Food type: ${feedType}`);
}

function handleEmergencyProtocol(button) {
  const protocolId = button.dataset.protocolId;

  console.log('ALARM! Activating emergency protocol');
  console.log(`Protocol: ${protocolId}`);
  console.log('Closing all gates...');
  console.log('Notifying staff...');
}

Calling preventDefault() blocks the link's normal navigation so that the panel can switch the view itself. Every handler reads the button's data through dataset: the markup says what to do, the functions know how.

Performance - Comparison

Ray shows performance tests. "Numbers don't lie, but everyone has to measure them on their own machine." The console.time() and console.timeEnd() functions measure the time between two calls with the same label.

// Test 1: Without delegation (separate listeners)
console.time('Assignment without delegation');

const cards1 = document.querySelectorAll('.card');
cards1.forEach(card => {
  card.addEventListener('click', function() {
    console.log('Clicked');
  });
});

console.timeEnd('Assignment without delegation');
// Time grows with the number of cards: 100 cards = 100 addEventListener calls

// Test 2: With delegation (one listener)
console.time('Assignment with delegation');

const container = document.getElementById('container');
container.addEventListener('click', function(event) {
  if (event.target.matches('.card')) {
    console.log('Clicked');
  }
});

console.timeEnd('Assignment with delegation');
// One addEventListener call, regardless of the number of cards

// Memory usage:
// Without delegation: a separate listener and a separate function for every card
// With delegation: one listener on the container

console.log('Number of listeners for 100 cards:');
console.log('Without delegation: 100');
console.log('With delegation: 1');
console.log('Measure exact time and memory in your browser DevTools');

We deliberately don't quote milliseconds or kilobytes, because they depend on the browser and the hardware. One thing is certain: without delegation, every new card adds another listener, and with delegation there is only one.

matches() vs closest() - Choosing the Method

"The two most important methods for delegation," Ray explains. Both take a CSS selector, but they look in different directions of the tree.

const container = document.getElementById('enclosure-list');

container.addEventListener('click', function(event) {
  const target = event.target;

  // matches() - checks if the element ITSELF matches
  if (target.matches('.enclosure-item')) {
    console.log('Clicked DIRECTLY on .enclosure-item');
    // Works only if exactly the element with the class was clicked
  }

  // closest() - searches upward to the first match
  const item = target.closest('.enclosure-item');
  if (item) {
    console.log('Clicked on .enclosure-item OR its child');
    // Works if the element or any of its children were clicked
  }
});

// HTML:
// <div class="enclosure-item">
//   <h3>T-Rex Enclosure</h3>           ← matches() NO, closest() YES
//   <p>Status: Active</p>              ← matches() NO, closest() YES
//   <button>Details</button>           ← matches() NO, closest() YES
// </div>                               ← matches() YES, closest() YES

// CONCLUSION: Use closest() for delegation - it's more flexible

The matches() method checks only the element itself, while closest() starts with it and walks up. That's why I recommend closest() as the default choice for delegation.

Complete Park Management System

"Let's combine everything into a working system," says Ray. One listener on the dashboard passes each click on to the class methods.

class JurassicParkManagementSystem {
  constructor() {
    this.selectedEnclosures = new Set();
    this.initialize();
  }

  initialize() {
    console.log('Initializing park management system');
    this.setupDelegation();
  }

  setupDelegation() {
    // One main listener for the entire dashboard
    const dashboard = document.getElementById('park-dashboard');

    dashboard.addEventListener('click', (event) => {
      this.handleDashboardClick(event);
    });

    console.log('Delegation system active');
  }

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

    // Handle different types of clicks
    this.handleActionButton(target) ||
    this.handleTabNavigation(target) ||
    this.handleStatusIndicator(target) ||
    this.handleEnclosureSelection(target);
  }

Each method returns true when the click belongs to it, and the || operator stops at the first true. That's why we ask the buttons first and the whole card last, just like in the gallery above. The arrow function keeps this pointing at the class instance.

  handleEnclosureSelection(target) {
    const enclosure = target.closest('.enclosure-card');
    if (!enclosure) return false;

    const enclosureId = enclosure.dataset.enclosureId;
    const enclosureName = enclosure.dataset.enclosureName;

    console.log(`Enclosure selected: ${enclosureName} (ID: ${enclosureId})`);

    // Toggle selection
    if (this.selectedEnclosures.has(enclosureId)) {
      this.selectedEnclosures.delete(enclosureId);
      enclosure.classList.remove('selected');
      console.log('Removed from selection');
    } else {
      this.selectedEnclosures.add(enclosureId);
      enclosure.classList.add('selected');
      console.log('Added to selection');
    }

    this.updateSelectionDisplay();
    return true;
  }

  handleActionButton(target) {
    const action = target.dataset.action;
    if (!action) return false;

    const enclosure = target.closest('.enclosure-card');
    const enclosureId = enclosure?.dataset.enclosureId;

    console.log(`Action: ${action} for enclosure: ${enclosureId}`);

    const actions = {
      'feed': () => this.feedDinosaur(enclosureId),
      'clean': () => this.cleanEnclosure(enclosureId),
      'maintenance': () => this.scheduleMaintenance(enclosureId),
      'emergency': () => this.activateEmergency(enclosureId)
    };

    const handler = actions[action];
    if (handler) {
      handler();
      return true;
    }

    return false;
  }

A Set stores the selection without duplicates, the actions object replaces a switch, and ?. prevents an error when the button isn't inside a card. Tabs and status indicators work the same way.

  handleTabNavigation(target) {
    if (!target.classList.contains('tab-button')) return false;

    const tabName = target.dataset.tab;
    console.log(`Switching to tab: ${tabName}`);

    // Remove active from all tabs
    document.querySelectorAll('.tab-button').forEach(tab => {
      tab.classList.remove('active');
    });

    // Add active to the clicked tab
    target.classList.add('active');

    // Show appropriate content
    this.showTabContent(tabName);
    return true;
  }

  handleStatusIndicator(target) {
    if (!target.classList.contains('status-indicator')) return false;

    const enclosure = target.closest('.enclosure-card');
    const enclosureId = enclosure?.dataset.enclosureId;

    console.log(`Showing status details for enclosure: ${enclosureId}`);
    this.showStatusDetails(enclosureId);
    return true;
  }

None of these elements has its own listener, because their clicks reach the dashboard anyway. At the end come the worker methods and the system start.

  feedDinosaur(enclosureId) {
    console.log(`Feeding dinosaur in enclosure: ${enclosureId}`);
  }

  cleanEnclosure(enclosureId) {
    console.log(`Cleaning enclosure: ${enclosureId}`);
  }

  scheduleMaintenance(enclosureId) {
    console.log(`Scheduling maintenance for enclosure: ${enclosureId}`);
  }

  activateEmergency(enclosureId) {
    console.log(`ALARM! Emergency protocol for enclosure: ${enclosureId}`);
  }

  showTabContent(tabName) {
    console.log(`Loading tab content: ${tabName}`);
  }

  showStatusDetails(enclosureId) {
    console.log(`Enclosure status details: ${enclosureId}`);
  }

  updateSelectionDisplay() {
    const count = this.selectedEnclosures.size;
    const display = document.getElementById('selection-counter');

    if (display) {
      display.textContent = `Selected: ${count} enclosures`;
    }

    console.log(`Currently selected enclosures: ${Array.from(this.selectedEnclosures).join(', ')}`);
  }
}

// System initialization
const parkSystem = new JurassicParkManagementSystem();

A single listener guards the whole dashboard, no matter how many enclosures appear on the screen.

Summary

"Event delegation," Ray concludes, "is not just an optimization. It's a fundamental technique in modern JavaScript. One listener handling thousands of elements - it's like a central monitoring system handling the entire park. Efficient, scalable, and easy to maintain."

Key rules:

  • Use closest() to find target elements
  • Check if the element is a child of the container with the listener
  • Use data-attributes for actions and identifiers
  • Remember to return after handling an event
  • Delegation automatically works with dynamic elements
  • Saves memory and improves performance

In the sandbox, the dragstart listener sits on the whole document, so the dinosaurs added every ten seconds can be dragged right away. Next lesson: mouse and keyboard events.

Remember: one sensor in the sector control center hears every enclosure, including the one built yesterday.

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>Drag & Drop - Moving Dinosaurs</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;
        }

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

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

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

        .enclosures-container {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
            margin-bottom: 30px;
        }

        .enclosure {
            background: rgba(0, 0, 0, 0.6);
            border: 3px dashed #7f8c8d;
            border-radius: 15px;
            padding: 20px;
            min-height: 300px;
            transition: all 0.3s ease;
        }

        .enclosure.drag-over {
            border-color: #3498db;
            background: rgba(52, 152, 219, 0.2);
            border-style: solid;
            transform: scale(1.02);
        }

        .enclosure h3 {
            text-align: center;
            margin-bottom: 20px;
            color: #ecf0f1;
        }

        .herbivore-enclosure {
            border-color: #27ae60;
        }

        .carnivore-enclosure {
            border-color: #e74c3c;
        }

        .herbivore-enclosure.drag-over {
            border-color: #2ecc71;
            background: rgba(46, 204, 113, 0.2);
        }

        .carnivore-enclosure.drag-over {
            border-color: #e74c3c;
            background: rgba(231, 76, 60, 0.2);
        }

        .dinosaur-card {
            background: linear-gradient(45deg, #34495e, #2c3e50);
            border-radius: 10px;
            padding: 15px;
            margin: 10px 0;
            cursor: grab;
            transition: all 0.3s ease;
            border: 2px solid transparent;
            user-select: none;
        }

        .dinosaur-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3);
        }

        .dinosaur-card.dragging {
            opacity: 0.5;
            transform: rotate(5deg);
            cursor: grabbing;
        }

        .dinosaur-card.herbivore {
            border-color: #27ae60;
        }

        .dinosaur-card.carnivore {
            border-color: #e74c3c;
        }

        .dino-header {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 10px;
        }

        .dino-emoji {
            font-size: 24px;
        }

        .dino-name {
            font-weight: bold;
            color: #ecf0f1;
        }

        .dino-info {
            font-size: 14px;
            color: #bdc3c7;
            margin: 5px 0;
        }

        .dino-diet {
            display: inline-block;
            padding: 3px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
        }

        .herbivore .dino-diet {
            background: #27ae60;
            color: white;
        }

        .carnivore .dino-diet {
            background: #e74c3c;
            color: white;
        }

        .drag-instructions {
            text-align: center;
            color: #bdc3c7;
            font-style: italic;
            margin: 20px 0;
        }

        .stats-panel {
            background: rgba(0, 0, 0, 0.8);
            border-radius: 10px;
            padding: 20px;
            margin-top: 30px;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
        }

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

        .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: #3498db;
        }

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

        .danger-warning {
            background: #e74c3c;
            color: white;
            padding: 10px;
            border-radius: 8px;
            margin: 10px 0;
            text-align: center;
            font-weight: bold;
            display: none;
        }

        @media (max-width: 768px) {
            .enclosures-container {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Moving Dinosaurs Between Enclosures</h1>

        <div class="instructions">
            <strong>Task:</strong> Drag dinosaurs to the appropriate enclosures based on their diet.<br>
            <span style="color: #27ae60;">β– </span> Herbivores β†’ Safe Enclosure |
            <span style="color: #e74c3c;">β– </span> Carnivores β†’ High Security Enclosure
        </div>

        <div class="enclosures-container">
            <!-- Enclosure for herbivores -->
            <div class="enclosure herbivore-enclosure" data-diet="herbivore" id="herbivore-enclosure">
                <h3>Safe Enclosure (Herbivores)</h3>
                <div class="drag-instructions">Drag herbivores here</div>

                <!-- Initial herbivore dinosaurs -->
                <div class="dinosaur-card herbivore" draggable="true" data-dino="triceratops" data-diet="herbivore">
                    <div class="dino-header">
                        <span class="dino-emoji">β—†</span>
                        <span class="dino-name">Triceratops</span>
                    </div>
                    <div class="dino-info">Length: 9m | Era: Cretaceous</div>
                    <span class="dino-diet">Herbivore</span>
                </div>

                <div class="dinosaur-card herbivore" draggable="true" data-dino="brachiosaurus" data-diet="herbivore">
                    <div class="dino-header">
                        <span class="dino-emoji">β—†</span>
                        <span class="dino-name">Brachiosaurus</span>
                    </div>
                    <div class="dino-info">Length: 23m | Era: Jurassic</div>
                    <span class="dino-diet">Herbivore</span>
                </div>
            </div>

            <!-- Enclosure for carnivores -->
            <div class="enclosure carnivore-enclosure" data-diet="carnivore" id="carnivore-enclosure">
                <h3>High Security Enclosure (Carnivores)</h3>
                <div class="drag-instructions">Drag carnivores here</div>
                <div class="danger-warning" id="danger-warning">
                    WARNING! Mixing carnivores and herbivores is dangerous!
                </div>

                <!-- Initial carnivore dinosaurs -->
                <div class="dinosaur-card carnivore" draggable="true" data-dino="trex" data-diet="carnivore">
                    <div class="dino-header">
                        <span class="dino-emoji">β—†</span>
                        <span class="dino-name">Tyrannosaurus Rex</span>
                    </div>
                    <div class="dino-info">Length: 13m | Era: Cretaceous</div>
                    <span class="dino-diet">Carnivore</span>
                </div>

                <div class="dinosaur-card carnivore" draggable="true" data-dino="velociraptor" data-diet="carnivore">
                    <div class="dino-header">
                        <span class="dino-emoji">β—†</span>
                        <span class="dino-name">Velociraptor</span>
                    </div>
                    <div class="dino-info">Length: 2m | Era: Cretaceous</div>
                    <span class="dino-diet">Carnivore</span>
                </div>
            </div>
        </div>

        <!-- Statistics panel -->
        <div class="stats-panel">
            <h3>Enclosure Statistics</h3>
            <div class="stats-grid">
                <div class="stat-item">
                    <div class="stat-value" id="herbivore-count">2</div>
                    <div class="stat-label">Herbivores</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value" id="carnivore-count">2</div>
                    <div class="stat-label">Carnivores</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value" id="total-moves">0</div>
                    <div class="stat-label">Total transfers</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value" id="safety-status">OK</div>
                    <div class="stat-label">Security status</div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let draggedElement = null;
        let totalMoves = 0;

        // Get references to elements
        const herbivoreEnclosure = document.getElementById('herbivore-enclosure');
        const carnivoreEnclosure = document.getElementById('carnivore-enclosure');
        const dangerWarning = document.getElementById('danger-warning');
        const herbivoreCount = document.getElementById('herbivore-count');
        const carnivoreCount = document.getElementById('carnivore-count');
        const totalMovesCount = document.getElementById('total-moves');
        const safetyStatus = document.getElementById('safety-status');

        // Event listeners for dragged element
        document.addEventListener('dragstart', function(e) {
            if (e.target.classList.contains('dinosaur-card')) {
                draggedElement = e.target;
                e.target.classList.add('dragging');

                console.log(`Started dragging: ${e.target.dataset.dino}`);

                // Setting the data for the transfer
                e.dataTransfer.setData('text/plain', e.target.dataset.dino);
                e.dataTransfer.effectAllowed = 'move';
            }
        });

        document.addEventListener('dragend', function(e) {
            if (e.target.classList.contains('dinosaur-card')) {
                e.target.classList.remove('dragging');
                draggedElement = null;
            }
        });

        // Event listeners for drop areas
        document.querySelectorAll('.enclosure').forEach(enclosure => {
            enclosure.addEventListener('dragover', function(e) {
                e.preventDefault(); // Allowing the drop
                e.dataTransfer.dropEffect = 'move';

                if (!this.classList.contains('drag-over')) {
                    this.classList.add('drag-over');
                }
            });

            enclosure.addEventListener('dragleave', function(e) {
                // Check if we're actually leaving the enclosure
                if (!this.contains(e.relatedTarget)) {
                    this.classList.remove('drag-over');
                }
            });

            enclosure.addEventListener('drop', function(e) {
                e.preventDefault();
                this.classList.remove('drag-over');

                if (draggedElement) {
                    const draggedDiet = draggedElement.dataset.diet;
                    const targetDiet = this.dataset.diet;
                    const dinoName = draggedElement.querySelector('.dino-name').textContent;

                    // Checking whether the dinosaur matches the enclosure
                    if (draggedDiet === targetDiet) {
                        // Moving the element
                        this.appendChild(draggedElement);
                        totalMoves++;

                        console.log(`${dinoName} moved to the right enclosure!`);

                        // Success animation
                        const movedCard = draggedElement; // dragend resets draggedElement before the second is up
                        movedCard.style.border = '2px solid #27ae60';
                        setTimeout(() => {
                            movedCard.style.border = '';
                        }, 1000);

                    } else {
                        // Invalid transfer
                        console.log(`ERROR: ${dinoName} cannot be in this enclosure!`);

                        // Error animation
                        const refusedCard = draggedElement;
                        refusedCard.style.border = '2px solid #e74c3c';
                        refusedCard.style.background = 'rgba(231, 76, 60, 0.3)';

                        setTimeout(() => {
                            refusedCard.style.border = '';
                            refusedCard.style.background = '';
                        }, 1000);

                        // Show warning
                        alert(`WARNING!\n\n${dinoName} cannot be placed in this enclosure!\n${draggedDiet === 'carnivore' ? 'Carnivores' : 'Herbivores'} must be in the appropriate enclosure for the park's safety.`);
                    }

                    updateStats();
                }
            });
        });

        // Function that updates the statistics
        function updateStats() {
            const herbivores = document.querySelectorAll('#herbivore-enclosure .dinosaur-card').length;
            const carnivores = document.querySelectorAll('#carnivore-enclosure .dinosaur-card').length;

            herbivoreCount.textContent = herbivores;
            carnivoreCount.textContent = carnivores;
            totalMovesCount.textContent = totalMoves;

            // Checking safety
            const herbivoreEnclosureHasCarnivores = document.querySelectorAll('#herbivore-enclosure .carnivore').length > 0;
            const carnivoreEnclosureHasHerbivores = document.querySelectorAll('#carnivore-enclosure .herbivore').length > 0;

            const isDangerous = herbivoreEnclosureHasCarnivores || carnivoreEnclosureHasHerbivores;

            if (isDangerous) {
                safetyStatus.textContent = '!';
                safetyStatus.style.color = '#e74c3c';
                dangerWarning.style.display = 'block';
            } else {
                safetyStatus.textContent = 'OK';
                safetyStatus.style.color = '#27ae60';
                dangerWarning.style.display = 'none';
            }

            // Check if all dinosaurs are in the correct enclosures
            const allInCorrectEnclosures = !isDangerous;
            if (allInCorrectEnclosures && totalMoves > 0) {
                setTimeout(() => {
                    alert('Congratulations!\n\nAll dinosaurs are now in the correct enclosures.\nThe park is safe!');
                }, 500);
            }
        }

        // Adding new dinosaurs after a few seconds
        function addNewDinosaur() {
            const newDinos = [
                {
                    name: 'Stegosaurus',
                    emoji: '',
                    diet: 'herbivore',
                    length: '9m',
                    era: 'Jurassic'
                },
                {
                    name: 'Allosaurus',
                    emoji: '',
                    diet: 'carnivore',
                    length: '9m',
                    era: 'Jurassic'
                }
            ];

            const randomDino = newDinos[Math.floor(Math.random() * newDinos.length)];

            const newDinoCard = document.createElement('div');
            newDinoCard.className = `dinosaur-card ${randomDino.diet}`;
            newDinoCard.draggable = true;
            newDinoCard.dataset.dino = randomDino.name.toLowerCase();
            newDinoCard.dataset.diet = randomDino.diet;

            newDinoCard.innerHTML = `
                <div class="dino-header">
                    <span class="dino-emoji">${randomDino.emoji}</span>
                    <span class="dino-name">${randomDino.name}</span>
                </div>
                <div class="dino-info">Length: ${randomDino.length} | Era: ${randomDino.era}</div>
                <span class="dino-diet">${randomDino.diet === 'herbivore' ? 'Herbivore' : 'Carnivore'}</span>
            `;

            // Add to incorrect enclosures for challenge
            if (randomDino.diet === 'herbivore') {
                carnivoreEnclosure.appendChild(newDinoCard);
            } else {
                herbivoreEnclosure.appendChild(newDinoCard);
            }

            updateStats();

            console.log(`Added a new dinosaur: ${randomDino.name}`);
        }

        // Adding a new dinosaur every 10 seconds
        setInterval(addNewDinosaur, 10000);

        // Initial statistics update
        updateStats();

        // Touch events for mobile devices (basic support)
        let touchItem = null;
        let touchOffset = { x: 0, y: 0 };

        document.addEventListener('touchstart', function(e) {
            if (e.target.classList.contains('dinosaur-card')) {
                touchItem = e.target;
                const touch = e.touches[0];
                const rect = touchItem.getBoundingClientRect();

                touchOffset.x = touch.clientX - rect.left;
                touchOffset.y = touch.clientY - rect.top;

                touchItem.style.position = 'fixed';
                touchItem.style.zIndex = '1000';
                touchItem.classList.add('dragging');

                e.preventDefault();
            }
        });

        document.addEventListener('touchmove', function(e) {
            if (touchItem) {
                const touch = e.touches[0];
                touchItem.style.left = (touch.clientX - touchOffset.x) + 'px';
                touchItem.style.top = (touch.clientY - touchOffset.y) + 'px';

                e.preventDefault();
            }
        });

        document.addEventListener('touchend', function(e) {
            if (touchItem) {
                const touch = e.changedTouches[0];
                const elementBelow = document.elementFromPoint(touch.clientX, touch.clientY);
                const enclosure = elementBelow ? elementBelow.closest('.enclosure') : null;

                if (enclosure) {
                    draggedElement = touchItem;

                    // Simulating a drop event
                    const dropEvent = new Event('drop');
                    enclosure.dispatchEvent(dropEvent);
                }

                // Reset styles
                touchItem.style.position = '';
                touchItem.style.left = '';
                touchItem.style.top = '';
                touchItem.style.zIndex = '';
                touchItem.classList.remove('dragging');

                touchItem = null;
                draggedElement = null;
            }
        });
    </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 are the main advantages of event delegation?

  2. 2. What is the difference between event.target and event.currentTarget?

Hands-on tasks in the game

  • Code editor

    The index.html file has a list of dinosaur cards #dino-list and a button that adds a new card after the page has loaded. Use event delegation: replace ___BLANK1___ with the variable of the container that holds the only click listener, and ___BLANK2___ with the method that starts at event.target and looks for the closest element matching the .dino-card selector. Clicking a card (also its inside and a card added later) should show the dinosaur name in #selected-dino, while the reserve card outside the list should not react.

  • Vertical ordering

    Arrange the steps for configuring event delegation:

  • Horizontal ordering

    Arrange the event delegation elements:

  1. QuestionQuiz: Event Delegation
  2. QuestionEvent.target vs Event.currentTarget
  3. Coding taskExercise: Event Delegation
  4. Put in orderEvent Delegation Configuration
  5. Put in orderEvent Delegation Syntax

Useful articles