2

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();
    }
});
Community
  • 1
  • 1
comebal
  • 946
  • 3
  • 14
  • 30
  • possible duplicate of [Detect click outside element?](http://stackoverflow.com/questions/1160880/detect-click-outside-element) – Ram Jul 31 '13 at 03:53

3 Answers3

1

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')
}) 
Akhil Sekharan
  • 12,467
  • 7
  • 40
  • 57
0
$('*').click(function(){
if($(this).has('#main-element') || $(this).parent().has('#main-element')){
// it will open here
}else{
//put your hide code
}
});
Sikander
  • 654
  • 1
  • 7
  • 21
0

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

lan.ta
  • 21
  • 1