Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do child element register a click event with a parent element in jquery? [duplicate]

Tags:

jquery

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();});

like image 770
Dan Avatar asked Oct 05 '11 00:10

Dan


People also ask

How do you only trigger parent click event when a child is clicked?

To only trigger parent click event when a child is clicked with JavaScript, we call stopPropagation . parent. addEventListener( "click", (e) => { e. stopPropagation(); console.

How to parent element in jquery?

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.

How do you check if an element is a child of a parent in JavaScript?

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); };


2 Answers

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.

like image 146
Lee Avatar answered Nov 15 '22 09:11

Lee


If you want to stop it from bubbling use

e.stopPropagation(); 
like image 44
aziz punjani Avatar answered Nov 15 '22 08:11

aziz punjani