exoslav
exoslav

Reputation: 2295

.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

Upvotes: 0

Views: 171

Answers (2)

Felix
Felix

Reputation: 38112

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

Upvotes: 4

devnull69
devnull69

Reputation: 16544

If you want to handle click on .inner different from click on .outer, you should have two event handlers. In the .inner click handler you can then prevent the event from bubbling up, so that clicking on .inner will not trigger the click event handler on .outer

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

$('.outer').on('click', function(e) {
   ...
});

Upvotes: 0

Related Questions