0

So I have a drop down menu:

JSFiddle Link: http://jsfiddle.net/cGt4h/3/

HTML:

<div id="container">
 <ul>
 <li>
 <a class='sign-in' href='#'>Login</a>
 <div id="loginForm" class='log-content'>
 <div>
 User name:
 <input type='text' />
 </div>
 <div>
 Password:
 <input type='text' />
 </div>
 <div>
 <input type='button' value='Login' />
 </div>
 </div>
 </li>
 </ul>
</div>

SCRIPT:

$('.sign-in').click(function(e) {
 e.preventDefault();
 $('#loginForm').toggle();
});
$("#loginForm").mouseup(function() {
 return false;
});
$(document).mouseup(function(e) {
 if ($(e.target).parent(".sign-in").length == 0) {
 $('#loginForm').hide();
 }
});

CSS:

#container {margin: 0 auto;width:400px; position:relative; }
#loginForm {
 width:200px;
 background-color:gray;
 color:white;
 padding:10px;
 display:none;
}
li {list-style: none;}
.sign-in {
 background-color:gray; 
 color:white;
 text-decoration:none;
}
.sign-in:hover {background-color:red;}
.open-menu {
 display:block !important;
 left:0;
}

It works fine but when I click on the .sign-in selector the dropdown doesn't close after it has been opened.

asked Nov 18, 2013 at 20:12

2 Answers 2

3

That's because your document.mousedown function is causing the form to hide, then your .sign-in click handler is toggling the form, causing it to show. This line:

if ($(e.target).parent(".sign-in").length == 0) {

evals to true, causing the form to hide, add an AND condition:

if ($(e.target).parent(".sign-in").length == 0 && $(e.target).attr("class") != "sign-in") {

Demo: http://jsfiddle.net/cGt4h/4/

answered Nov 18, 2013 at 20:18
Sign up to request clarification or add additional context in comments.

Comments

-1

Try this:

$('.sign-in').click(function(e) {
 e.stopPropagation();
 e.preventDefault();
 $('#loginForm').toggle();
});
$("#loginForm").mouseup(function() {
 return false;
});
$(document).mouseup(function(e) {
 if ($(e.target).parent(".sign-in").length == 0 && $(e.target).attr("class") != "sign-in") {
 $('#loginForm').hide();
 }
});
answered Nov 18, 2013 at 20:34

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.