Reputation: 4795
<!DOCTYPE html>
<html>
<head>
<script src="jquery-2.1.1.min.js" type="text/javascript"></script>
</head>
<body>
<div id="outer">
<div id="inner">
</div>
</div>
<script type="text/javascript">
$("#outer").on("myevent", function(event) {
alert(event.target.id);
event.stopPropagation();
return false;
});
$("div").trigger("myevent");
</script>
</body>
</html>
In the code above I expect the event myevent
to be handled once by outer
div. But I see two alerts: outer
and then inner
. Why stopPropagation
does not work here and how do I prevent propagating custom events to children?
EDIT: I want to trigger event globally, like $("div").trigger("myevent");
but I want to handle it only there where I subscribed to it.
Upvotes: 3
Views: 1064
Reputation: 92983
Instead of using event.stopPropagation()
on $('#outer').on('myevent')
, you need to use it on every div
element in a separate handler:
$("#outer").on("myevent", function(event) {
console.log(event.target.id);
return false;
});
$('div').on('myevent', function(event) { // or $('*').on('myevent', ...
event.stopPropagation();
});
$("div").trigger("myevent"); // only logs 'outer'
http://jsfiddle.net/mblase75/z7NQy/
Upvotes: 3
Reputation: 28523
You are getting two alerts because you are triggering myevent
on div
and hence it will apply to all div
available in html. In this case you have inner and outer div
which triggers myevent
one by one.
To trigger myevent
on outer div use :
$("div#outer").trigger("myevent");
Upvotes: 1
Reputation: 782508
$("div").trigger("myevent");
is equivalent to:
$("div").each(function() {
$(this).trigger("myevent");
});
because jQuery automatically loops over all the elements that match the selector. So it's triggering the event on the inner and outer DIVs separately.
When it triggers it on the inner DIV, there's no handler there, so nothing stops the event from bubbling to the outer DIV.
To stop this from happening, you should be more specific about the element you're triggering on:
$("#outer").trigger("myevent");
Upvotes: 2