if I've got a floating message box and i'm wondering if clicking paragraph text within that box will also register a click on it's parent element in jQuery or if i have to add click listeners for the child elements as well.
update: here's the basic layout:
<div id='msgbox'>
<p>This is the <span>message</span></p>
</div>
Now if i click the text in the <p>
or in the <span>
will it still trigger as a click on $('#msgbox')
?
update 2: Can I stop this behavior??
update 3: here's the fiddle i've got going: http://jsfiddle.net/MZtbY/ - now is there a way to stop propagation after it reaches a certain level? so clicking the <p>
would be ok, but clicking the <span>
would do nothing? - sort of like $('#msgbox :nth-child').click(function(e) {e.stopPropagation();});
To only trigger parent click event when a child is clicked with JavaScript, we call stopPropagation . parent. addEventListener( "click", (e) => { e. stopPropagation(); console.
The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree. To traverse all the way up to the document's root element (to return grandparents or other ancestors), use the parents() or the parentsUntil() method.
To check if an element is a child of a parent with JavaScript, we can use the parent element's contains method. const contains = (parent, child) => { return parent !== child && parent. contains(child); };
Here's an example at jsFiddle
$('#msgbox').click(function(evt){
alert("click on msgbox: "+evt.target);
});
// stop bubbling for the span only.
$('#msgbox span').click(function(evt) {
evt.stopPropagation();
});
Note that clicking on the #msgbox <div>
(that's the red box in the jsFiddle), or on the first section of the paragraph text will both trigger the event handler on #msgbox; but clicking on the text inside the <span>
will not. This is because we've applied a handler directly to the span, and called stopPropagation()
on that event to prevent the normal bubbling action.
Update: here's an update to your fiddle that shows the same thing.
If you want to stop it from bubbling use
e.stopPropagation();
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