I want to fire an event when I click on a div, but i don't want that event to fire if i click on a specific link on that div:
my JS
$("#myDiv").not("#myLink").click(function () {
alert("clicked");
});
//Or
$("#myDiv:not(#myLink)".click(function () {
alert("clicked");
});
$("body").on('click', '#myLink', function(e) {
e.stopPropagation();
});
my HTML
<div id="myDiv">
<a href="#" id="myLink">Some link</a>
</div>
Here is jsfiddle
EDIT: Actually my real code is with "On" method, I've already tried stopPropagation but it doesn't work in that case
In order to get your desired result you have to register an event handler on the anchor element, that when executed blocks the event propagation.
$("#myLink").click(function(e) {
e.stopPropagation();
});
Why this work?
Events propogate starting from the root element till the target element (capture phase) and after reaching the target, they climb up back to the root element (bubbling phase). The target element is the element that received the event.
It's possible to register event listeners both on the capture phase, both on the bubbling phase. Here, we're using jQuery that registers the event on the bubbling phase.
stopPropagation
permits to block the event propagation through the DOM.
That's an article I wrote, in case you need more info about W3C event model.
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