Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check with javascript/jquery if i clicked inside div?(i did research in here-i need better)

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.

like image 219
Hižko Hiiž Avatar asked Jan 18 '23 16:01

Hižko Hiiž


1 Answers

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');
  });
like image 149
lincolnk Avatar answered Jan 31 '23 07:01

lincolnk