Search code examples
jqueryevent-bubbling

how jQuery event bubbling works?


I have the following HTML code:

<ul id="level1">
     <li id="level21">item1</li>
     <li id="level22">item2</li>
</ul>

I tried to do event bubbling for the child class <li> using jQuery:

$(document).ready(function(){
    $('#level1').on('click', function(event){
         alert($(this) + ',' + event);
    });
});

This code does not trigger event bubbling for both <li> class. Is this because the child classes do not have click events for them? I still don't understand when event bubbling would be triggered?


Solution

  • The <ul> element is wrapping the <li> elements, that's why the alert triggers when you click either of the items. Same happens for every DOM element that you attach a click event to - all child elements will trigger the event when clicked on (unless you stop the propagation by calling event.stopPropagation()).

    It has, at the moment, nothing to do with event bubbling. As the comments state correctly, bubbling is when the event triggers for the element, and then trigger for parent elements in sequence.

    Your comment is also correct. If you attached an event for an li, you'll see two alerts as you can see in this Fiddle I made.