Javascript Hide Element when clicking anywhere on the page

I have a JS sliding menu that opens when you click the "noty_menu" link and then closes when you click that link again. Is there a way to set it so that the menu closes when you click ANY on the page?

Here's the relevant code:

$('.noty_menu').click(function () {
$('ul.the_menu').slideToggle('medium');
});

      

Thanks in advance!

+3


source to share


3 answers


You can click on the body:

$('body').click(function() {
    /* close menu */
});

      

But then in your menu, click to prevent the click from spreading over the body. Otherwise, the menu will open, the click will extend upward, and the menu will immediately close. return false;

should be enough:

$('.noty_menu').click(function () {
    $('ul.the_menu').slideToggle('medium');
    return false;
});

      



(You can also read the handler function in the event argument, for example function(ev) { ... }

and call ev.stopPropagation()

).

You can also prevent clicks from being closed inside the menu:

$('ul.the_menu').click(function () {
    return false;
});

      

Note that this solution has a caveat that any other click event that stops propagation will also prevent the menu from closing.

+4


source


u can use

$('body').click(function(){
//ur code
});

      



to do this

+2


source


You can check the entire document, however it includes menu clicks (if you have spacing, this can annoy the user) something like this:

var menu=$('ul.the_menu');
$(document).on('click',function(){
    if(menu.height>0) {
        menu.slideToggle('medium');
    }
});

      

+2


source







All Articles