Reputation: 12054
Here is my fiddle:
https://jsfiddle.net/rpq6swu2/
<div id="container" onclick="alert('clicked in container')">
<div id="div1" >Something inside the other div</div>
</div>
// div1 is added dynamically normally inside the container.
$(document).on('click', '#container #div1', function(e) {
e.stopPropagation();
e.stopImmediatePropagation();
alert('clicked in div1 only');
})
I cannot modify the html part: it was done by someone else.
Upvotes: 0
Views: 63
Reputation: 2875
I've come across this problem myself in the past. The problem is that "click" is an amalgamation of two events: mousedown
and mouseup
. Just change the "click" to "mousedown" and it should work as expected, as you can see in the snippet below (just the same as your code but with the one change).
$(document).on('mousedown', '#container #div1', function(e) {
e.stopPropagation();
e.stopImmediatePropagation();
alert('clicked in div1 only');
})
#container {
background-color: red;
width: 640px;
height: 640px;
}
#div1 {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container" onclick="alert('clicked in container')">
<div id="div1" >Something inside the other div</div>
</div>
----- EDIT -----
I want to point out that I believe this issue is only because of how jQuery .on() works – I think there's a difference between its understanding of "click" and the native click event.
Read this discussion by much cleverer people than myself here:
https://github.com/jquery/jquery/issues/3693
So you could just use a native javascript event handler and the click event propagation is stopped. Or use jQuery event handlers for both divs. I think it's the mix that's causing the issue.
Here's a snippet using just native javascript:
function onDiv1Click(e) {
e.stopPropagation();
alert('div 1 clicked');
}
#container {
background-color: red;
width: 640px;
height: 640px;
}
#div1 {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container" onclick="alert('clicked in container')">
<div id="div1" onclick="onDiv1Click(event)">Something inside the other div</div>
</div>
And here using just jQuery
$(document).on('click', '#container', function(e) {
alert('clicked in container');
})
$(document).on('click', '#container #div1', function(e) {
e.stopPropagation();
alert('clicked in div1 only');
});
#container {
background-color: red;
width: 640px;
height: 640px;
}
#div1 {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<div id="div1" >Something inside the other div</div>
</div>
You see both options work
Upvotes: 2