I'd like to hide a div when user click anywhere on the page outside of that div. How can I do that using raw javascript or jQuery?
+1
A:
First idea, in raw javascript (from this post):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<style type="text/css">
<!--
#mydiv{
background-color: #999999;
height: 100px;
width: 100px;
}
-->
</style>
<script type="text/javascript">
document.onclick=check;
function check(e)
{
var target = (e && e.target) || (event && event.srcElement);
var obj = document.getElementById('mydiv');
if(target!=obj){obj.style.display='none'}
}
</script>
</head>
<body>
<div id="mydiv">my div</div>
</body>
</html>
Tested with IE6 and FireFox3.1, it does work as advertised.
VonC
2008-11-26 16:10:55
+11
A:
Attach a click event to the document to hide the div:
$(document).click(function(e) {
$('#somediv').hide();
});
Attach a click event to the div to stop clicks on it from propagating to the document:
$('#somediv').click(function(e) {
e.stopPropagation();
});
Eran Galperin
2008-11-26 16:16:02
Thanks a lot! That worked just the way I wanted it to.
sumek
2008-11-27 10:03:52
AFAIK, with jQuery in the second event handler you only need to "return false;" to stop the propagation. http://docs.jquery.com/Events/click (near the bottom of the page)
scunliffe
2009-12-09 15:49:06
A:
It sure sounds like you want a modal dialog. This jQuery plugin http://code.google.com/p/simplemodal/ looks like it has potential.
Eric Wendelin
2008-11-26 16:49:34