Search code examples
javascriptbootstrap-accordion

Javascript - event.stopPropagation() not working from parent to child on BS4 accordion


I am using BS4 accordion with nesting each other.

I have faced event bubbling with parent to child and child to parent both I have solved one that is from child to parent using the event.stopPropagation() but event bubbling from parent to child is not stopped why?

Here is the code

$('.card > .collapse').on('shown.bs.collapse', function(e){
    e.preventDefault();  
    e.stopPropagation();
      $(this).parent().find(".flaticon-down-arrow").removeClass("flaticon-down-arrow").addClass("flaticon-right-arrow");

  }).on('hidden.bs.collapse', function(e){
    e.preventDefault();  
    e.stopPropagation();
    $(this).parent().find(".flaticon-right-arrow").removeClass("flaticon-right-arrow").addClass("flaticon-down-arrow");

})

Here is my codepen link

Note: - Inspect to the changes of classes


Solution

  • Event bubbling only goes up the DOM tree (from child to parent, to grandparent, etc). It does not go down the DOM tree. Thus, any event on the parent will never bubble to its children.

    The documentation states that during event bubbling (for a click event):

    The browser checks to see if the element that was actually clicked on has an onclick event handler registered on it in the bubbling phase, and runs it if so. Then it moves on to the next immediate ancestor element and does the same thing, then the next one, and so on until it reaches the element.