Search code examples
jqueryevent-bubblingstoppropagation

.stopPropagation() and bubbling - can someone explain it to me?


I have a stupid question. Can somebody explain me, why event still starts on .outer? Even when I have set .stopPropagation(). I suppose, I don't understand the issue correctly. When I click on .inner, event should not bubble up to .outer

HTML:

<div class="outer">asdsad
    <div class="inner">asdadsasd</div>
</div>

JavaScript:

$('.outer').on('click', function(e) {
    e.stopPropagation();
    $('.inner').toggleClass('hidden');
})

Fiddle


Solution

  • You need to use:

    $('.inner').on('click', function (e) {   
        e.stopPropagation();
    })
    
    $('.outer').on('click', function (e) {   
        $('.inner').toggleClass('hidden');    
    })
    

    since e.stopPropagation() prevent event buble up not down the DOM tree

    Updated Fiddle