I want to stop propagate event from parent div
to child div
in my html. Here a simple code what I'm trying to do:
<div>
<div id='categoryList'>
<div class='listed-category'>
<span>some content</span>
<a id='close'>x</a> //"a" is used to remove the div
</div>
</div>
</div>
<div id='dropdown'>
</div>
In the above code if I click on <div id='categoryList'>
the <div id='dropdown'>
will slide-up and down by bellow code.
$(document).ready(function () {
$('#categoryList').click(function (event) {
event.preventDefault();
event.stopPropagation();
if ($('#dropdown').is(":visible")) {
$('#dropdown').slideUp(400);
}
else {
$('#dropdown').slideDown(400);
}
});
})
But when I click on the child <div class='listed-category'>
the above JavaScript executes and the <div id='dropdown'>
is sliding up and down. How to stop this? Yet I want to be able to click on <a id='close'>
to remove the child div
stopPropagation() Event Method The stopPropagation() method prevents propagation of the same event from being called. Propagation means bubbling up to parent elements or capturing down to child elements.
Event.stopPropagation() The stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. It does not, however, prevent any default behaviors from occurring; for instance, clicks on links are still processed.
If you use event. stopPropagation() , sure it will stop any parent events from firing.
To stop an event from further propagation in the capturing and bubbling phases, you call the Event. stopPropation() method in the event handler. Note that the event. stopPropagation() method doesn't stop any default behaviors of the element e.g., link click, checkbox checked.
Check target for match clicked object. Try this code in beginning of click event handler.
if( event.target !== this ) {
return;
}
//...do stuff..
A more elegant solution is to use CSS and disable the pointer events on the children.
#categoryList * {
pointer-events: none;
}
Or in your specific case to have no events on the listed-category
element:
#listed-category {
pointer-events: none;
}
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