Event Propagation and Delegation in JavaScript


  Event propagation is the mechanism by which an event occurring on an element can be handled by its parent elements, whileEvent delegation allows you to efficiently handle events on parent elements without needing to add multiple event handlers to the children.


Syntax:


  Let's look at a basic example of how event propagation and delegation behave:

document.getElementById('parent').addEventListener('click', function(event) {
  alert('Parent element clicked!');
  event.stopPropagation();
});

document.getElementById('child').addEventListener('click', function(event) {
  alert('Child element clicked!');
});

document.getElementById('parent').innerHTML = '<div id="child">Click here</div>';

Purpose:


  Event propagation is useful when we want an event on a child to affect its parents. Event delegation facilitates handling events on multiple child elements without having to assign an individual handler to them.



Exercises



The rest of the content is available only for registered and premium users!



What is event delegation?



JavaScript Concepts and Reference

What is event delegation and propagation in JavaScript? What is event delegation in JavaScript? What is the difference between event delegation and event propagation? How does event propagation work? JavaScript events JavaScript event delegation Trigger JavaScript event JavaScript mouse events JavaScript browser events Advanced JavaScript examples Move HTML elements with JavaScript JavaScript scroll event