javascript - Prevent nested elements from triggering an event for parent element -


structure:

.parent (has if/else toggle on click) -> .child (has nothing)

<div class="parent">parent     <div class="child">child</div> </div> 

the parent element styled hide overflowing content , toggle height on click. when user clicks, parent element expand show child element. want users able click on child element without parent element toggling original size , hiding child element. want toggle happen on parent.

i realize child element still contained within parent element's clickable area, there way exclude it?

solution 1: compare target currenttarget:

$("#parentele").click( function(e) {     if(e.target == e.currenttarget) {         alert('parent ele clicked');     } else {         //you exclude else block have nothing within listener         alert('child ele clicked');     } }); 

fiddle

e.target element started event.
e.currenttarget (bubbling up) parentele in click event that's listening for.

if same, know click directly on parent.


solution 2: stop propagation before event hits parentele:

the other option prevent event bubbling in first place if there click on child element. can done this:

$("#parentele").click( function(e) {     alert('parent ele clicked'); }); $("#parentele").children().click( function(e) {     //this prevent event bubbling event higher direct children     e.stoppropagation(); }); 

fiddle


the main difference between 2 first solution ignore event in listener , allow keep bubbling up. may necessary if have parent of parentele needs event.

the second solution stops click events bubbling past parentele's direct children. if there click event on parent of parentele, never see these events either.


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -