Close a div when clicking outside the div area

I have this piece of code. I am trying to close a div when it is clicked outside of the Div, I have been looking through this forum but cannot find a solution. Here is the violin 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()
+4
source share
4 answers

Div reqwidth - 100% of the screen. Width framematches 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>
Run codeHide result
+5
source

Please check it.

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

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

Test code here is jsfiddle

+2
source

.is() , - jQuery.

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

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

Here is a working jsFiddle . (Note that this will not work if you click to the right of the div, but that is because you are still clicking on #reqbecause it does not have the specified width.)

+2
source

You need to add a click event to the document and check that the target clicked, and any of them parent does not have the required class:

$(document).on('click', function (e) {
  var divClass = 'my-class';
  if (!$(e.target).hasClass(divClass) && !$(e.target).parents().hasClass(divClass)) {
    // do something...
  }
});
Run codeHide result
0
source

All Articles