开发者

jQuery Toggle on mouseup

I have the following jQuery:

$('#account-menu').hide();

$("#account-link").click(function(e) {
     e.preventDefault();
     $("#account-menu").toggle();
     $("#account-link").toggleClass("selected");
});

What I want to do is check if the user clicks anywhere else onscreen WHILST THE ACCOUNT MENU IS SHOWN BUT not within the account menu itself, and if so then hide the menu. Can anyone help?

Thanks

EDIT: I had a go at doing this myself like so:

$('#account-menu').hide();

    $("#account-link").click(function(e) {
        e.preventDefault();
        $("#account-menu").toggle('fast');
        $("#account-link").toggleClass("selected");
    });

    $(document).mouseup(function(e) {
        var $targ = $(e.target);

        // if we are the link or the box, exit early
        if ($targ.is('#account-link') || $targ.is('#account-menu')) return;
        // if we have a parent who is either, also exit early
        if ($targ.closest('#account-link, #account-menu').length) return;

        // hide the box, uns开发者_如何转开发elect the link
        $("#account-link").removeClass("selected");
        $("#account-menu").hide('fast');
    });

But wanted to see if there was a nicer and much smaller (code-wise) way of doing it.


Use jQuery to hide a DIV when the user clicks outside of it


Maybe something like this...

$('#account-menu').hide();

$('body').click(function(){
    $("#account-menu:visible').toggle();
    $("#account-link").removeClass("selected");
});

$("#account-link").click(function(e) {
    e.preventDefault();
    $("#account-menu:not:visible").toggle();
    $("#account-link").addClass("selected");
});

UPDATE

So this won't fully work, since the body click triggers when you click the link too. This is a step in the right direction though. G/L

UPDATE #2

I finally got this working over on JSFiddle.net, using the comments from Joseph Le Brech (+1). Check out the live Demo. I could not get the $('body') selector working on there, so I am simulating the body with a div called bodyDiv. It's all commented and working 100%. Happy Coding.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜