Reputation: 981
Hi following is my html.
// consider all are of same size
<div id="grand-parent">
<div id="parent">
<div id = "child">
</div>
</div>
</div>
Javascript.
$("#grand-parent").click(function(){
alert("grand-parent");
});
$("#parent").click(function(){
alert("grand-parent");
});
// consider this as child event but actual child event comes from third party.
$("#parent").click(function(){
return false;
});
The events are bind in the order of child, parent, grand-parent. Now when i click on div child element event will trigger first return false. This will stop event bubbling. But I want the grand-parent div click event also needs to be triggered.
Blockers: Child click event will always bind first and it is third party api so we cant touch.
Any Help can be appreciated.
Upvotes: 0
Views: 1997
Reputation: 343
The solution is to use the useCapture
parameter of addEventListener
when registering on the grand-parent.
This will call the grand-parent event before calling the child's event.
See the doc for addEventListener.
Upvotes: 1
Reputation: 2107
You can use below code, if you click on child then first grand parent will trigger, then child and then parent. If you click on parent, grand parent event will trigger, then parent and if you click on grand parent, it will trigger grand parent only. In this code i am applying event capturing concept, so grand parent will call first then, control goes to child then parent.
JS fiddle link -
https://jsfiddle.net/oe1qxsub/
HTML -
<div id="grand-parent">
<div id="parent">
<div id = "child">
</div>
</div>
</div>
JS -
$("#grand-parent").get(0).addEventListener("click", function(){
alert("grand-parent");
}, true);
$("#parent").click(function(){
alert("parent");
});
$("#child").click(function(){
alert('child');
});
CSS -
#grand-parent{
background:blue;
width:80px;
height:80px;
}
#parent{
background:red;
width:50px;
height:30px;
}
#child{
background:yellow;
width:20px;
height:20px;
}
Upvotes: 1