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 that the user clicks nowhere on the screen AFTER INDICATING THE ACCOUNT MENU , but not inside the account menu itself, and if so, hide the menu. Can anyone help?

thank

EDIT: I myself did it like this:

$('#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, unselect the link
        $("#account-link").removeClass("selected");
        $("#account-menu").hide('fast');
    });

But I wanted to see if there was a way to make it more beautiful and much smaller (code-wise).

+3
source share
2 answers

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

Thus, this will not fully work, since triggers click on the body when you click on the link too. This is a step in the right direction. G / l

UPDATE # 2

- JSFiddle.net, Joseph Le Brech (+1). -. $('body') , div bodyDiv. 100%. .

+1

Source: https://habr.com/ru/post/1791485/


All Articles