wawanopoulos
wawanopoulos

Reputation: 9794

Show div on click on button, then hide this div when clicking outside of it

HTML

<div id="selectPeriodRangePanel">
    <p>Test</p>
</div>

<button id="period_select_range_btn">Select Range</button>

JQUERY

$("#period_select_range_btn").off().on("click", function(){
    $("#selectPeriodRangePanel").toggle();
});

When i click on button, the selectPeriodRangePanel DIV is opened. I would like to hide this DIV when i click outside of it.

How can i do that ?

Upvotes: 9

Views: 16496

Answers (3)

Jai
Jai

Reputation: 74738

I would do it like:

Try this

$(document).on("click", function(e) {
  var el = $(e.target).closest("#selectPeriodRangePanel, #period_select_range_btn").length != 0;
  $("#selectPeriodRangePanel").toggle(el);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="selectPeriodRangePanel" style="display:none">
  <p>Test</p>
</div>

<button id="period_select_range_btn">Select Range</button>

Upvotes: 3

kpucha
kpucha

Reputation: 729

Try this

$(document).on("click", function(e){
    if($(e.target).is("#period_select_range_btn")){
      $("#selectPeriodRangePanel").show();
    }else{
        $("#selectPeriodRangePanel").hide();
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="selectPeriodRangePanel" style="display:none">
    <p>Test</p>
</div>

<button id="period_select_range_btn">Select Range</button>

Upvotes: 13

Arun P Johny
Arun P Johny

Reputation: 388316

You can have a click handler for the document element, where if the click has happened outside then you can hide it.

$("#period_select_range_btn").off().on("click", function() {
  $("#selectPeriodRangePanel").toggle();
});
$(document).click(function(e) {
  if ($(e.target).closest('#selectPeriodRangePanel, #period_select_range_btn').length == 0) {
    $("#selectPeriodRangePanel").hide();
  }
})
body {
  min-height: 500px;
  background-color: lightblue;
}
#selectPeriodRangePanel {
  background-color: lightgrey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="selectPeriodRangePanel">
  <p>Test</p>
</div>

<button id="period_select_range_btn">Select Range</button>

Upvotes: 5

Related Questions