开发者

How to untoggle a dropdown by clicking elsewhere in the page - stopPropagation?

I wonder if anyone can help to finally resolve an issue I brought up on SO a while back.

I am unable to untoggle these dropdown menus by clicking outside of the button, or anywhere else on the page.

Please see this jsFiddle.

I've seen folks using stopPropagaton() but am unsure how to apply it here.

Any ideas how to do this?

My toggling code:

var cur = null;
$(".toggle").click(function(e){
    $('#nav ul:visible').hide();

    i开发者_StackOverflowf(cur == null || cur.currentTarget != e.currentTarget)
    {
        if(cur != null)
        {
            $(cur.currentTarget)
                .children('a:first').children('span').removeClass('fc-state-active');
        }

        cur = e;
        $(cur.currentTarget)
            .children('a:first').children('span').addClass('fc-state-active');
        $(cur.currentTarget)
            .children('ul').show();
    }
    else
    {
        $(cur.currentTarget)
            .children('a:first').children('span').removeClass('fc-state-active');

        cur = null;
    }
});


I believe the following should work for you. This utilizes jQuery's focusout() function:

$(".toggle").click(function(){
    $('#nav ul:visible').hide();
    $('span.fc-state-active').removeClass('fc-state-active');
    $(this).children('a:first').children('span').addClass('fc-state-active');
    $(this).children('ul').show();
}).focusout(function(){
    $('#nav ul:visible').hide();
    $('span.fc-state-active').removeClass('fc-state-active');
});

And here's an updated fiddle: jSFiddle

EDIT: The following works in FF & Chrome New Fiddle: jsFiddle

$(".toggle").click(function(){
    $('#nav ul:visible').hide();
    $('span.fc-state-active').removeClass('fc-state-active');
    $(this).children('a:first').children('span').addClass('fc-state-active');
    $(this).children('ul').show();
    hide = false;
}); 
$(document).click(function(){
    if(hide){
        $('#nav ul:visible').hide();
        $('span.fc-state-active').removeClass('fc-state-active');
    }
    hide = true;
});

Reason: $(document).click() is called after $(".toggle").click()

EDIT 2: The working fiddle can be found here: jSFiddle

var hide;
$(".toggle").click(function(){
    var active_span = $(this).children('a:first').children('span');   
    var active_ul = $(this).children('ul');

    $(active_span).toggleClass('fc-state-active');
    $("span.fc-state-active").not(active_span).removeClass('fc-state-active');
    $(active_ul).toggle();
    $("#nav ul:visible").not(active_ul).hide();
    hide = false;   
});
$(document).click(function(){
    if(hide){
        $('#nav ul:visible').hide();
        $('span.fc-state-active').removeClass('fc-state-active');
    }
    hide = true;
}); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜