1

I am trying to implement a bit of code that Twitter use to toggle off the drop-down login box when a user clicks outside the scope of the drop-down box itself.

I am having a bit of trouble, currently if I click outside the scope of the element it works as expected but the same thing also happens when I click inside the element scope I.e. within the #form element.

HTML Markup:

<body>
    <div id="form">
        <div id="form-tab"></div>
        <div id="form-header">FooBar</div>
        <form>
            <label>Test</label>
            <input type="text">
        </form>
    </div>
</body>

jQuery Code:

$(document).mouseup(function(e) {
    if ($(e.target).parent("div#form").length==0) {
        hide();
    }
});

function hide() {
    $element.animate({
        right: $rightPos
    }, 1000);
}

If anyone can help me figure out where I am going wrong it would be greatly appreciated.

Thanks in advance.

zealisreal
  • 495
  • 2
  • 8
  • 20

2 Answers2

2

Create a click handler for the body element that hides the form. Create a click handler for the form that stops propagation of the click event. That way if you click inside the form, the event doesn't bubble up to the body event click handler.

$('body').click( function() {
     hide();
});

$('#form').click( function(e) {
    e.stopPropagation();
});
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
0

try:

$(':not(#form)').mouseup(function(e) {
        hide();
});

http://api.jquery.com/not-selector/

Ankur
  • 12,676
  • 7
  • 37
  • 67
  • I see the logic behind that and hoped it would be the one to sort this, but sadly it made no difference, the #form element still hid when clicked on. – zealisreal Oct 31 '11 at 12:41