I have 2 elements nested called blanket and blanket-content and I want to recognize the clicks done to the parent alone.
<div id="blanket">
<div id="blanket-content"></div>
</div>
The issue that I'm having is that when I'm clicking the child it is triggering the parent on click. I've tried different methods yet I was unsuccessful. I have tried these to play around with my code;
$('#blanket').on('click', function(ev) {
alert(ev.currentTarget.id); //
});
^ This triggers the click on div as normal and state the parent id even when the child is clicked.
$('#blanket-content').on('click', function(ev) {
alert(ev.currentTarget.id);
});
^ This doesn't trigger anything
What I want to achieve is when I click on blanket-content nothing will happen, but when I click on blanket I want to do something.
One easy solution is to stop the event propagation in a click handler of the blanket-content, so that it will trigger the parent element's click handler.
You can use Event.stopPropagation() to do that
$('#blanket').on('click', function(ev) {
alert(ev.currentTarget.id); //
});
$('#blanket-content').on('click', function(ev) {
ev.stopPropagation()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="blanket">blanket
<div id="blanket-content">blanket-content</div>
</div>
Another solution(why) is to check whether the click happened in the blanket-content element inside the blanket click handler
$('#blanket').on('click', function(ev) {
if (!$(ev.target).closest('#blanket-content').length) {
alert(ev.currentTarget.id); //
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="blanket">blanket
<div id="blanket-content">blanket-content</div>
</div>
No need to do more. Just add ev.stopPropagation(); inside #blanket-content click event.
<div id="blanket">PARENT
<div id="blanket-content">CHILD</div>
</div>
$('#blanket').on('click', function(ev) {
alert(ev.currentTarget.id); //
});
$('#blanket-content').on('click', function(ev) {
ev.stopPropagation();
alert(ev.currentTarget.id);
});
Check here: https://jsfiddle.net/92jwad1w/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With