Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 964
wawanopoulos Avatar asked Jan 22 '16 13:01

wawanopoulos


People also ask

How do you show a div for 10 seconds and then hide it?

Select the div element. Use delay function (setTimeOut(), delay()) to provide the delay to hide() the div element.

Can you give a div an onclick?

To set an onClick listener on a div element in React:Set the onClick prop on the div. The function you pass to the prop will get called every time the div is clicked. You can access the div as event. currentTarget .


2 Answers

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>
like image 67
Arturo Avatar answered Oct 09 '22 20:10

Arturo


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>
like image 24
Arun P Johny Avatar answered Oct 09 '22 18:10

Arun P Johny