Fel AA
Fel AA

Reputation: 325

Jquery stopPropagation not working, two cases

$(document).on('click', '.outer1', function(){
    alert('outer click event');
})

$(document).on('click', '.inner1', function(e){
    e.stopPropagation();
    alert('inner click event');
})

$('.outer2').on('click', function(){
    alert('outer click event');
})

$(document).on('click', '.inner2', function(e){
    e.stopPropagation();
    alert('inner click event');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer1">
   <div class="inner1"> Case 1 - Click Here</div>
</div>


<div class="outer2">
   <div class="inner2"> Case 2 - Click Here</div>
</div>

For example, modal window:

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

First case:

$(document).on('click', '.outer', function(){
    alert('outer click event');
})

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

Second case:

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

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

What is the difference? Why stopPropagation() working in first case, but not working in second case?

Upvotes: 3

Views: 63

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

The latter doesn't work because the event needs to bubble up through the DOM from .inner to document for it to be caught by the delegated event handler.

However, it's caught by the event handler on .outer as it bubbles up and this is before the stopPropagation() call has been made.

Upvotes: 1

Related Questions