Here's a full-fledged event-driven approach
- Custom events handle the "summoning" and "dismissing" of the layer as to not step on the toes of other click-based events
- document.body listens to for a dismiss event only when the layer in question is actually visible
Zee code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(function()
{
var $layer = $('#layer');
var $body = $('html');
$layer
.bind( 'summon', function( e )
{
$layer.show();
$body.bind( 'click', dismissLayer );
} )
.bind( 'dismiss', function( e )
{
$layer.hide();
$body.unbind( 'click', dismissLayer );
} )
.click( function( e )
{
e.stopPropagation();
})
.trigger( 'dismiss' )
;
function dismissLayer( e )
{
$layer.trigger( 'dismiss' );
}
// This is optional - this just triggers the div to 'visible'
$('#control').click( function( e )
{
var $layer = $('#layer:hidden');
if ( $layer.length )
{
$layer.trigger( 'summon' );
e.stopPropagation();
}
} );
});
</script>
<style type="text/css">
#layer {
position: absolute;
left: 100px;
top: 20px;
background-color: red;
padding: 10px;
color: white;
}
#control {
cursor: pointer;
}
</style>
</head>
<body>
<div id="layer">test</div>
<span id="control">Show div</span>
</body>
</html>
It's a lot of code I know, but here just to show a different approach.