Tuesday, September 14, 2010

jQuery: hide div when click outside

Useful for log-in popups/dropdown menus/links

<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8" />
<title>jQuery: hide div when click outside</title>

<style type="text/css">
a{
text-decoration: underline;
color: blue;
cursor: pointer;
}
.headerLogin{
background: #fe0000;
position: absolute;
top: 40px;
left: 50px;
z-index: 2;
padding: 6px;
margin: 0 -4px 0 0;
width: 200px;
border-radius: 5px;
-moz-border-radius: 5px 5px 5px 5px;
-webkit-border-radius: 5px 5px 5px 5px;
display: none;
}
</style>


<script type="text/javascript" src="jquery-1.4.2.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){

$(".headerLoginLink").click(function(){
$(".headerLogin").slideDown('slow', function() {
// Animation complete.
});
/*
if ($(".headerLogin").is(':hidden'))
$(".headerLogin").show();
else{
$(".headerLogin").hide();
}
return false;
*/
});

$('.headerLogin, .headerLoginLink').click(function(e) {
e.stopPropagation();
});
$(document).click(function() {
//$('.headerLogin').hide();
$(".headerLogin").slideUp('slow', function() {
// Animation complete.
$(".headerLogin").fadeOut('slow');
});

});

});
</script>

</head>

<body>

<a class="headerLoginLink">Login</a>

<div class="headerLogin">
<span>
<input type="text" value="email" onfocus="if(this.value=='email'){this.value=''}" onblur="if(this.value==''){this.value='email'}" />
<input type="password" value="password" onfocus="if(this.value=='password'){this.value=''}" onblur="if(this.value==''){this.value='password'}" />
</span>
<b class="fBeforeLoginText"><input type="checkbox" /> remember &nbsp; <a href="#">forgot password</a></b> <br />
<span><input type="button" value="login" /></span>
</div>


</body>

</html>