Skip to content
Advertisement

Direct vs delegation and bubbling vs capturing in jQuery

HTML

<div>
 <span></span>
 <span></span>
 <span></span>
 <span></span>
</div>

jQuery

$('div span').on('click', function(){
  //direct - 1st method
});

$('div').on('click','span', function(){
  //delegation - 2nd method
});

I have used both above method in my code. I know second method is better due to it has only got single handler. My problems are:

  1. Is first method (direct) refers to the concept called event capturing? Is it an example for event capturing?
  2. Is second method (delegation) refers to the concept called event bubbling? Is it an example for event bubbling?

Advertisement

Answer

$('div span').on('click', function(){
  //direct - 1st method
});

This event only attached the event handler to the spans inside Div that are currently present in the DOM.. i.e; if a new span element is added to the div , that span will not have a click event associated with it..

The first and second one are example’s of Event Bubbling

There comes the concept of Event delegation where in the ancestor is given the event handler and it is delegated to the children..

The second example is an example of event delegation . Wherein event is attached to the parent element..So all the span element’s inside the div class are attached to the event handler ..

So if a new span element is added to the div , becoz the event is associated with the span’s ancestor the event will fire in this case

This helps in cases

$('div').on('click','span', function(){
  //delegation - 2nd method
});

I have no idea where event capturing is used in the jQuery library

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement