Tasha Jordan
Tasha Jordan

Reputation: 21

jquery close container if anything except container and button is clicked

I have a button and group, when button is clicked group should show, when anything except group is clicked group should close. My code below is not working

<body>
    <div id="btn" class="control">
    <div id="group" class"control">
</body>

      $("#btn").click(function(){
        $("#group").toggle();
      });

$("body").click(function(evt){    
    if(!$(evt.target).is(".control")) {
        $("#group").hide();
    }

I can't put target as #group as this would cancel the toggle when button is clicked.

Using the code above the group shows when button is clicked but hides when anything on screen is clicked, including when button and group is clicked.

How can I get the jquery to work as expected?

Thanks

Upvotes: 0

Views: 61

Answers (2)

ikiK
ikiK

Reputation: 6532

If I understood you good this is what you need? You can do this without class control, just with two ids. It will throw an error but that's exactly what we want. The code does as required. jQuery.noop()

$("#group").click(function(){
 $("#group").noop();
});
$("#btn").click(function(){
 $("#group").toggle();
});
$("div").not("#btn").click(function(){    
   $("#group").css("display", "none")
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div>EVERYTHING ELSE 
EVERYTHING ELSE </br>
EVERYTHING ELSE 
EVERYTHING ELSE </br>
EVERYTHING ELSE 
EVERYTHING ELSE</br>
EVERYTHING ELSE EVERYTHING ELSE
</div>
    <div id="btn">-----btn----</div>
    <div id="group"  style="display:none">-----group----</div>
 <div>
EVERYTHING ELSE
EVERYTHING ELSE</br>
EVERYTHING ELSE
EVERYTHING ELSE</br>
EVERYTHING ELSE EVERYTHING ELSE
 </div>   
</body>

Upvotes: 0

Elman Huseynov
Elman Huseynov

Reputation: 1147

Try this code please:

$(document).on('click', function(e) {
  var target = $(e.target);
  if (target.is('#btn')) {
    $(".group").toggleClass('hide');
  } else if (target.is('#group')) {
    if ($(".group").hasClass('hide')) {
      $(".group").removeClass('hide');
    }
  } else {
    $(".group").addClass('hide');
  }
})
#btn {
  width: 100px;
}

.group {
  width: 100px;
  height: 100px;
  background-color: red;
  display: block;
}

.group.hide {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn" class="control">Click me</button>
<div id="group" class="group hide"></div>

Upvotes: 2

Related Questions