0PricingLogin
jQuery Academy · Lesson

Implementing Robust Event Delegation

Learn the principles and benefits of event delegation using .on() to handle events for multiple and future elements with a single listener, improving performance.

What is Event Delegation?

Welcome to event delegation! This powerful technique helps you manage events efficiently in your web applications.

Instead of attaching many event listeners to individual elements, you attach a single listener to a common parent element. It's like having one 'supervisor' watching over all its 'children' for specific actions.

Direct Binding: A Limitation

When you bind events directly to elements using .on() or other methods, the listener is only attached to elements that exist at that exact moment. Any new elements added to the DOM later won't automatically get the event handler.

In the example, try clicking the initial buttons. Then, after a short delay, a new button appears. Try clicking the new button – it won't respond!

$(document).ready(function() {
  // Assume basic HTML structure like:
  // <div id="my-list">
  //   <button class="item">Button 1</button>
  //   <button class="item">Button 2</button>
  // </div>

  // Direct binding to existing items
  $('.item').on('click', function() {
    $(this).text('Directly clicked!');
  });

  // Simulate adding a new item after initial binding
  setTimeout(function() {
    $('#my-list').append('<button class="item">New Item</button>');
    console.log('A new item was added after 2 seconds.');
    console.log('Try clicking the new item - it wont respond!');
  }, 2000);
});

All lessons in this course

  1. Implementing Robust Event Delegation
  2. Stopping Event Propagation
  3. Creating and Triggering Custom Events
← Back to jQuery Academy