I have a parent element DIV that has children div elements. I have separate click implementations for parent and its children.
<div id="mainContainer">
<div id="childContainer">
</div>
<div id="childContainer2">
</div>
</div>
$('#mainContainer').click(function () {
console.log('main container');
}).children().click(function () {
console.log('childen');
return false;
});
$('#childContainer2').click(function () {
console.log('child container 2');
});
This is working fine. but if I click a child then the event runs twice which is how it is supposed to work. My question is - Is there a way that I can explicitly write event to parent that would not affect children so that children need not execute click function twice?
If your child element is located inside your parent element you could also just add this CSS property. This way the click directly triggers the parent's click event listener.
By a adding an onClick function for the child modal (content div) mouse click events are prevented to reach the 'closeLogin' function of the parent element.
An element receives a click event when a pointing device button (such as a mouse's primary mouse button) is both pressed and released while the pointer is located inside the element.
event.stopPropagation() This will stop any parent component's event from firing. To use this: Make sure to pass the event object as a parameter. Use the stopPropagation method on the event object above your code within your event handler function.
yes you can just, change the order of binding the events and to stop propagation use stopImmediatePropagation
consider this fiddle
$('#childContainer2').click(function (e) {
alert('child container 2');
e.stopImmediatePropagation()
return false;
});
$('#mainContainer').click(function () {
alert('main container');
}).children().click(function (e) {
alert('childen');
return false;
});
You can use use event.stopPropagation:
children().click(function (e) {
e.stopPropagation();
console.log('childen');
return false;
});
to prevent event buble up
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