How to hide a div when the mouse is clicked outside the div
I've a HTML div and I want to hide it whenever the user clicks on the page anywhere outside the div. Which clicking on which element should I trig开发者_运维百科ger the onclick event??
$('#mydiv').click(function(e) { e.stopImmediatePropagation(); });
$(document.body).one("click", function() {
$('#mydiv').hide();
});
Since mydiv
is also a child of the body
element, you don't want that when clicking on that element, the element would dissappear.
So when people click on the mydiv
, you want it to stop bubbling up to the body
element, that is why first you register a click event on your mydiv
, and tell it to stop bubbling.
Assuming you're 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, unless you click on the div'.
Re: Toggle button
Then you'll 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');
});
The BODY element.
精彩评论