How do I detect a click outside an element?

0

I have some HTML menus, which I show when a user clicks on these menus. I would like to hide these elements when the user clicks off from the menu area.

How could I do this?

    
asked by anonymous 06.09.2018 / 20:52

1 answer

1

add a class .menus then jquery:

$('body').on('click', function () { // Pega o clique
    if (!$(this).hasClass('menus')) { //Se o objeto clicado não possuir a classe, então o clique foi fora dos menus
        $('.menus').hide(); // esconde os menus
    }
});
    
06.09.2018 / 21:15