Event Delegation is a powerful jQuery technique where you attach an event handler to a parent element instead of attaching it to individual child elements. This works especially well for dynamically added elements.
.on()Instead of binding events directly to elements, you bind them to a parent that exists at page load. The event bubbles up and is handled at the parent level.
// Syntax of event delegation
$(parentSelector).on(event, childSelector, function() {
// event handling logic
});
// Attach click event using delegation
$("#list").on("click", "li", function() {
// This will work for existing and future li elements
$(this).css("color", "red");
});
Clicking on any list item (even dynamically added ones) will change its color to red because the event is handled by the parent element.
Notice: New items respond to clicks immediately without re-binding events.
// Dynamically add list items and handle clicks
$("#addItem").click(function() {
$("#list").append("<li>New Item</li>");
});
.on() over older methods like .delegate()