How to hide a div when the mouse is pressed outside the div

I have an HTML div and I want to hide it whenever the user clicks on a page outside the div. Which click on which element should I trigger the onclick event?

+3
source share
3 answers

Assuming you are using the latest jQuery, v1.4.4:

$(<the div you want hidden>).click(false); //stop click event from bubbling up to the document
$(document).one('click', function(){
  $(<the div you want hidden>).hide(); //which will hide the div
});

In other words, this code says: "Hide the div if you click on this page, if you don't click on the div."

Re: Toggle button

Then you will have something like:

$('button').click(function(){
  $('div').toggle();
});
$('div').click(false);
$(document).click(function(){
  $('div').hide();
  //reset the toggle state, e.g.
  $('button').removeClass('selected');
});
+1
source
$('#mydiv').click(function(e) { e.stopImmediatePropagation(); });
$(document.body).one("click", function() {
    $('#mydiv').hide();
});

mydiv body, , .
, mydiv, , body, click mydiv , .

+6

BODY element.

0
source

Source: https://habr.com/ru/post/1777397/


All Articles