Johan Cruijff
Johan Cruijff

Reputation: 183

Close div by clicking outside using fadeToggle

I'm using fadeToggle to open/close a div. How can I close the div by clicking anywhere outside?

I've tried the following:

var dropDown = jQuery('.dropdown-menu');

jQuery('.menu-nav').click(function () { 
    dropDown.fadeToggle('fast');
});

jQuery('div:not(.menu-nav, .dropdown-menu)').click(function () { 
    dropDown.fadeOut('fast');
});

What happens is that the div opens and closes immediately. Is this even possible with fadeToggle?

Upvotes: 2

Views: 2459

Answers (2)

Bojangles
Bojangles

Reputation: 101473

This quite a common requirement. You want to bind a click event to the document, then see if that click event's target is inside your menu or not, in this case using .closest():

var dropDown = jQuery('.dropdown-menu');

// Show the menu
jQuery('.menu-nav').click(function () { 
    dropDown.fadeIn('fast');
});

// Hide the menu
jQuery(document).click(function (e) { 
    if(!jQuery(e.target).closest('.menu-nav').length || !jQuery(e.target).hasClass('dropdown-menu') {
        dropDown.fadeOut('fast');
    }
});

Upvotes: 1

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

Attach an event handler to the click event on the document. When a click occurs check the target to determine if either the .dropdown-menu or .menu-nav was clicked. If not, then hide the menu.

var dropDown = jQuery('.dropdown-menu');

jQuery('.menu-nav').click(
    function (e) { 
        dropDown.fadeToggle('fast');
        e.preventDefault();
    }
);

 jQuery('div:not(.menu-nav, .dropdown-menu)').click(
    function (e) { 
        dropDown.fadeOut('fast');
        e.preventDefault();
    }
);

$(document).on("click", function(e){
    var $target = $(e.target);
    if(!$target.is(".menu-nav") && !$target.is(".dropdown-menu")){
        dropDown.fadeOut('fast');
    }
});

Working Example: http://jsfiddle.net/UJNd5/

Upvotes: 2

Related Questions