I am in dire need of your assistance yet again.
So basically i have a div, id="parent", which i want to be able to hide along with its contents, I've also nested a div inside this div, with an id of "nested". "Parent" is wider than "nested" so what I want to happen is that when you click on "parent" i want the hide function to activate, but if you click on "nested" this hide function doesn't activate.
However what is happening is that the function activates when you click on "parent" and when you click on "nested". Here is the code:
HTML:
<div id="parent">
<div id="nested">
<p>Contents</p>
</div>
</div>
JQUERY: (put a console.log there 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 cant figure it out! Are my selectors wrong? Is this something JQuery simply can't do?? Any help much appreciated!
Thank you!
Events always bubble up. So if you click on the nested div it will bubble up that click event to the parent.
If I understood you correctly you only want to execute the click event when the parent was clicked and not the nested div itself.
Just validate that the current event was infact triggered by the parent and only then execute the code.
EDIT
Updated to use event.target instead, as apparently event.srcElement
is 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...");
}
});
I would not recommend attaching click events to every single div you want to ignore. That is way to much maintenance and very error prone when eventually actions are required on the nested divs.
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