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>

2 comments:

  1. Amazing code!!! wery well!

    but why i can't use it for 2 separate div ?
    -for example "login" and "profile"???



    remaeis@gmail.com
    -thanks!!!!

    ReplyDelete
  2. This is wonderful! I spent 2 hours on the web to find a working example! Copied and pasted the code, worked straight away!

    Hint: replace all the dots (.) with (#) in the Javascript and then all the "class=" with "id=" in the HTML code. For headerLogin add an extra id="headerLogin" in the HTML next to the "class=". Now it works with IDs instead of classes! I find it easier to work this way.

    ReplyDelete