catandmouse
catandmouse

Reputation: 11829

Hiding a dropdown when there's a click outside of it (jQuery)

I am using this code to hide a dropdown when I click outside of it:

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

$('#ddbox').click(function(event){
      event.stopPropagation();
});

It's working. However, I have another link that shows/hides this dropdown. And when I use the above code, I need to click on that link twice for the dropdown to appear. This is the show/hide code for the dropdown:

$('#ddtrigger').toggle(function() {
     $('#ddbox').show();
}, function() {
     $('#ddbox').hide();
});

What could be the problem?

EDIT (this is the HTML):

<a href="#" id="ddtrigger">Some link</a>

<div id="ddbox">

    <p>Some text</p>

</div>

Upvotes: 1

Views: 2847

Answers (3)

Gaurav Mehra
Gaurav Mehra

Reputation: 139

may be you will find this usefull...

$(document).mouseup(function(e){
    if($( e.target ).parent( 'Object_to_hide' ).length == 0 ) {
        Object_to_hide.hide();
    }
});

i once used this and it worked great...

Upvotes: 0

Sico
Sico

Reputation: 1183

Can you not use the jquery blur event on the dropdown to hide it?

Upvotes: 0

Moe Sweet
Moe Sweet

Reputation: 3721

I think it's .toggle problem. You have 2 links. So those toggle functions for those 2 are not synced. Why don't u change .toggle into something like this.

$('#ddtrigger').click(function() {
     $('#ddbox').toggle();
});

Upvotes: 1

Related Questions