jQuery - How to make the fadeout menu when the user clicks anywhere else in the document outside the menu itself?

advertisements

I have a link that functions similar to a drop down menu in that it fades in a list of links below it when clicked. Currently, the list fades back out when the link is clicked again, but I'd like for it to also fade out if the user clicks elsewhere on the page. I'm not sure how to add the $(document).click(function()... that handles this, or if this is even the right approach. Here is my code:

$('#show_button').click( function(){
    if(!$('#list').is(':visible')){
        var pos = $('#show_button').offset();
        $('#list').css({'left':pos.left - 11, 'top': pos.top+14}).fadeIn();
    }
    else{
        $('#list').fadeOut();
    }
});

I am trying to add something like this to make the list fade out when the user clicks anywhere else in the page:

if($('#list').is(':visible')){
    $(document).click(function() {
        $('#list').fadeOut();
    });
}

Thanks in advance - I would appreciate any help on this one :)


You can check the element that the event is targeting and see if the id is equal to list. If it is not, then fadeOut() list

$(document).click( function(e){
    if (e.target.id != "list") $("#list").fadeOut();
});