Jquery when clicking on div but not nested div

I need your help again.

So basically I have a div, id = "parent", which I want to hide along with its contents, I also nested the div in this div with the identifier "nested". The “parent” is wider than the “nested” one, so I want to press the “parent” button to want the hide function to be activated, but if you click the “nested” ones, this hide function will not be activated.

However, what happens is that the function is activated when you press "parent" and when you press "nested". Here is the code:

HTML:

<div id="parent"> <div id="nested"> <p>Contents</p> </div> </div> 

JQUERY: (put console.log to represent the hide function)

 var parent = $('#parent'); var nested = $('#nested'); parent.not(nested).click(function(){ console.log('Click'); }); 

It seems like it should be simple, but I can't figure it out! Are my selectors wrong? Is this something jQuery just can't do? Any help is much appreciated!

Thanks!

+4
source share
2 answers

Events are always bubbling. Therefore, if you click on a nested div, it will trigger a click event for the parent.

If I understand you correctly, you want to execute the click event only when the parent clicks, and not in the nested div itself.

Just confirm that the current event was infact triggered by the parent, and only then execute the code.

EDIT
Updated to use event.target , since event.srcElement apparently not cross-browser compatible.

 var parent = $('#parent'); parent.click(function(event){ if(event.target === this){ console.log("parent was clicked and we execute actions..."); } else{ console.log("something else within parent was clicked and is ingored..."); } });​ 

Demo

I would not recommend adding click events for every div you want to ignore. This is a way to do a lot of maintenance and is very error prone when in the end actions are required for nested divs.

+13
source

Try

 $('#nested').click(function(e) { e.stopPropagation(); }); 
+5
source

Source: https://habr.com/ru/post/1436950/


All Articles