JavaScript Hide Element When Clicking Anywhere on Page

javascript, jquery, jquery-events

Solution

You could catch a click on the body:

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

But then in your menu click you have to prevent propagation of the click up to body. Otherwise the menu will open, the click will propagate up, and the menu will immediately close. `return false;` should suffice here:

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

(You could also read in the event argument to the handler function like `function(ev) { ... }` and call `ev.stopPropagation()`).

You may also want to prevent clicks inside the menu from closing it:

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

Note that this solution comes with a caveat that any other click event that stops propagation will also prevent the menu close.

Problem

I have a sliding JS menu that opens when you click the noty_menu link, then closes when you click that link again. Is there a way to set it so that the menu closes when you click ANYWHERE on the page? Here's the relevant code: ``` $('.noty_menu').click(function () { $('ul.the_menu').slideToggle('medium'); }); ```

Original source