comebal
comebal

Reputation: 946

How to detect a click outside an element, but that element got children

I know this question might be repetitive as I have seen this solution: How do I detect a click outside an element?

I want to remove #main-element if I click outside the element, BUT, that element also has child elements inside. Meaning, if I click one of the child of #main-element, #main-element should not close

<div id="main-element">
    <div class="test">1</div>
    <div class="test">2</div>
    <div class="test">3</div>
    <div class="test">4</div>
</div>

I tried using this solution:

$('html').click(function(e){
    if(e.target.id !== 'main-element') {
       $("#main-element").removeClass("open").hide();
    }
});

// For the trigger
$("#click-show").click(function(){
    if($("#main-element").hasClass("open"))
    {
       $("#main-element").removeClass("open").hide();
    }
    else{
       $("#main-element").addClass("open").show();
    }
});

Upvotes: 2

Views: 2481

Answers (3)

lan.ta
lan.ta

Reputation: 21

try to refer to function of jquery is HasClass('your child element class') with jquery.click(document)

Upvotes: 0

Sikander
Sikander

Reputation: 656

$('*').click(function(){
if($(this).has('#main-element') || $(this).parent().has('#main-element')){
// it will open here
}else{
//put your hide code
}
});

Upvotes: 0

Akhil Sekharan
Akhil Sekharan

Reputation: 12683

This might help:

DEMO

Use closest to loop through parents and classes to show/hide your element;

$('html').on('click', function(){
  var mainElement = $('#main-element');
  if($(this).closest(mainElement).length){
      return;
  }
  mainElement.addClass('main-element-closed')
}) 

Upvotes: 1

Related Questions