Gromain
Gromain

Reputation: 123

Testing if a click is in a div and all its children

I am facing an issue about this.

<div id="1">
    <div id="2">
    </div>
    <div id="3">
        <div id="4">
        </div>
    </div>
</div>

<div id="others_div">
</div>

I want to add the class "hidden" to "1" when I click on something which is not "1" nor one of its children.

Now I am using this but I have a lack of imagination for solving this issue...

document.onclick = function(e)
{
    if(e.target.id!="1")
    {
        $("#1").addClass("hidden");
    }
}

Upvotes: 3

Views: 71

Answers (4)

The Process
The Process

Reputation: 5953

Well, to avoid e.stopPropagation() (maybe you want that event to bubble up to some other ancestor) You can check if it is not clicked on #1 nor on it's children like this:

$('body').on('click', function(e) {

     if (!((e.target.id== "1") || $(e.target).closest('#1').length)) {
       $("#1").addClass("hidden");
     }    
  });

Upvotes: 4

zarpio
zarpio

Reputation: 7338

I think you want this

// taken from http://stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element

$('html').click(function() {
	//Hide the menus if visible
  alert('hide');
});

$('#one').click(function(event){
    event.stopPropagation();
});
div#one {
  background: yellow;
}

div#others_div {
  background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<div id="one">
  div one
  <div id="2">
    div two
  </div>
  <div id="3">
    div three
    <div id="4">
      div four
    </div>
  </div>
</div>

<div id="others_div">
  other div
</div>

Upvotes: 0

Rion Williams
Rion Williams

Reputation: 76547

You could use a jQuery check like the following one to check if the current element is your 1 element or traverse the DOM to see if the current target is contained within an element with an ID of 1 :

<script>
      $(function(){
          // Trigger this when something is clicked
          $(document).click(function(e){
              // Toggle the hidden class based on if the current element is 1
              // or if it is contained in an element with ID of 1
              $("#1").toggleClass('hidden',!((e.target.id== "1") || $(e.target).closest('#1').length))
          });
      });
</script>

Generally, you should avoid using ID attributes that only consists of numbers as they are not valid (ID attributes must begin with a letter). Ignoring this could result in some issues with regards to CSS or jQuery selection.

Upvotes: 1

Korgrue
Korgrue

Reputation: 3478

JQuery

$('body').on( "click", function(e) {
  if(e.target.id !== "1")
    {
        $("#1").addClass("hidden");
    }
});

Upvotes: 0

Related Questions