user3903810
user3903810

Reputation: 19

How to close dropdown box with Jquery when clicking outside

So I have this dropdown box, I would like to close it when clicking outside of it, how can I get it?

 $(document).ready(function(){
    jQuery('ul.nav li.dropdown').click(function() {
        jQuery(this).find('.dropdown-menu').fadeIn();

        $("#actionStatus").html("");


        });
        $("body:not(ul.nav li.dropdown)").hover(function(){
$("ul.nav li.dropdown").find('.dropdown-menu').fadeOut();
});

    $("#btnSendOption").click(function(){
        var data = $("#frmUserOption").serialize();
        $.ajax({
            url: "/users.php",
            data: data,
            success: function( data ) {
                $("#actionStatus").html("");
                $("input[type='radio']").attr('checked', false);
                $('.dropdown-menu').delay(1000).fadeOut();
            },
            error: function(data) {
                $("#actionStatus").html("<div class='alertMsg alertMsg-danger'>Error, try again later</div>");
            }
        });
    });
});

Any help is very appreciated. Thank you in advance.

Upvotes: 0

Views: 446

Answers (3)

Scott Mitchell
Scott Mitchell

Reputation: 698

I created a simple jsbin for you with an example of what I think you need. I added some simple html as reference just guessing what you needed...

http://jsbin.com/bodoxixa/1/edit?html,js,output

Upvotes: 1

Nitesh Saxena
Nitesh Saxena

Reputation: 199

You can use this:

$("body:not(ul.nav li.dropdown)").hover(function(){
    $("ul.nav li.dropdown").find('.dropdown-menu').fadeOut();
})

Upvotes: 1

reyaner
reyaner

Reputation: 2819

maybe something like this: (didnt test it)

$(document).ready(function(){
    $('ul.nav li.dropdown').click(function() {
        var $this = $(this);
        $("body").one("click",":not('ul.nav li.dropdown')", function(){
             $this.find('.dropdown-menu').fadeOut();
        });
        $this.find('.dropdown-menu').fadeIn();
        $("#actionStatus").html("");
    });
});

Upvotes: 1

Related Questions