How do you check whether the click on a page was inside a certain <div>
or not?
I have a <div>
with nested children, so $("div").click()
technique doesn't work because clicking on other elements inside won't trigger anything.
What i need exactly is this: I click on 1 element on a page and show the other more complex <div>
. When I click outside of this <div>
, I need it to hide.
This seems simple, but I've been unable to solve it for a few hours now.
I can't use focus/blur because it outlines the element.
What I need is this: I click on 1 element—in this case a link—then assign it a class. I then put the same class on the parent of the link. This is because I need to show which <div>
is a sibling of the link.
In my CSS, I have something like parent.class{ mydiv{display:block;} })
.
When I click somewhere else on the page, I need to delete those classes. The problem is when I click inside the shown <div>
, my function thinks I clicked somewhere on the page and deletes the classes.
I think your best bet is to set a click handler for the page and work your way up whenever it fires.
$(document).click(function(e) {
var d = e.target;
// if this node is not the one we want, move up the dom tree
while (d != null && d['id'] != 'myDiv') {
d = d.parentNode;
}
// at this point we have found our containing div or we are out of parent nodes
var insideMyDiv = (d != null && d['id'] == 'myDiv');
});
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