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();
    }
});
1

3 Answers 3

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')
}) 
Sign up to request clarification or add additional context in comments.

1 Comment

That looks nothing at all like what he asked.
0
$('*').click(function(){
if($(this).has('#main-element') || $(this).parent().has('#main-element')){
// it will open here
}else{
//put your hide code
}
});

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.