Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

close div when clicked outside the div area

Tags:

jquery

I have this piece of code.I am trying to close the div,when clicked outside the Div,I have searched through this forum but can not find a solution -Here is a fiddle- Demo

$('#hideshow1').on("click", function() {
    var text = $(this).val();
    $("#req").toggle();

});

$(window).on("click keydown", function(e) {
  //e.preventDefault() /*For the Esc Key*/
  if (e.keyCode === 27 || !$(e.target).is(function() {return $("#req, #hideshow1")})) {
    $("#req").hide()
  }
}).focus()
like image 456
kunz Avatar asked Mar 08 '16 01:03

kunz


3 Answers

Div req width is 100% of screen. The frame width is the same as the border.

$('#hideshow1').on("click", function() {
  if ($("#frame").is(":visible") == false) {
    $("#frame").show();
  }
  $('#hideshow1').text("Click outside div to hide it.");
});
$(document).mouseup(function(e) {
  var container = $("#frame"); //Used frame id because div(req) width is not the same as the frame 
  if ($("#frame").is(":visible")) {
    if (!container.is(e.target) //check if the target of the click isn't the container...
      && container.has(e.target).length === 0) {
      container.hide();
      $('#hideshow1').text("Click to see div");
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="clickme">
  <a class="req_pic_link" id="hideshow1">Click outside div to hide it.</a>
</div>
<div id="req">
  <iframe id="frame" src="https://www.google.com"></iframe>
</div>
like image 186
Reagan Gallant Avatar answered Nov 19 '22 17:11

Reagan Gallant


Please check this out.

$('html').click(function() {
  $("#req").hide();
  // add some code
});

$('#clickme').click(function(event) {
  event.stopPropagation();
  // add some code
});

Test code here jsfiddle

like image 29
aldrien.h Avatar answered Nov 19 '22 16:11

aldrien.h


The function argument for .is() is used to test every element in the set, and needs to return a boolean value as to whether the element matches or not - it should not return a jQuery collection.

However for what you are trying to do you should only pass a selector instead of a function to .is() like this:

if (e.keyCode === 27 || !$(e.target).is("#req, #hideshow1")) {
    $("#req").hide()
}

Here is a working jsFiddle. (Note that it won't work if you click to the right of the div, but that is because you are still clicking on #req because it doesn't have a specified width.)

like image 25
Ken Herbert Avatar answered Nov 19 '22 18:11

Ken Herbert