pentester pentester - 5 months ago 21
CSS Question

How can I make my toggle menu close when I click away?

I'm am struggling to get the drop down to close when I click away.

It only closes when I click the the parent.

$("#nav > ul > li").on('click', function(){
$(this).toggleClass('active');
});


http://jsfiddle.net/2mRwb/3/

What's the best solution in this case?

Answer

Here's how you'd do that

$('#nav > ul > li').on({
    mouseenter: function() {
        $('a', this).addClass('hover');
    },
    mouseleave: function() {
        if (! $(this).hasClass('active') )
            $('a', this).removeClass('hover');
    },
    click: function(){
        $('.active').not(this).removeClass('active');
        $('.hover').not( $(this).find('a') ).removeClass('hover');
        $(this).toggleClass('active');
    }
});

$(document).on('click', function(e) {
    if ( $(e.target).closest('#nav .active').length === 0 )
        $('.active').removeClass('active').find('a').removeClass('hover');
});

FIDDLE

Fixed a few other issues as well

Comments