DOM - Event delegation (bubbling, propagation)

About

Event delegation allows to:

  • attach a single event listener to a element
  • and to apply it to all descendants matching a selector,
  • whether those descendants exist now or are added in the future.

events are attached by default to the elements

Using event propagation (bubbling) to handle events at a higher level in the DOM than the element on which the event originated.

You bubbles up or down the DOM

Example

Jquery

  • The html where we will attach the same callback function to all descendant anchors (a) of ul
<ul>
  <li><a href="#">First</a></li>
  <li><a href="#">Second</a></li>
  <li><a href="#">Third</a></li>
</ul>
$( "ul" ).on( "click", "a", function( event ) {
    event.preventDefault();
    console.log( $( this ).text() );
});
  • Result

Documentation / Reference


Powered by ComboStrap