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>
- The below javascript:
- select the ul element,
- calls the jquery on function
- for a click event
- applied to all descendant anchors (a). (The second value is also a selector)
- a callback function that:
- prevent the default action (ie navigation)
- and prints the inner text of the anchor
$( "ul" ).on( "click", "a", function( event ) {
event.preventDefault();
console.log( $( this ).text() );
});
- Result