Check in the html click event that the click did not originate from within the menu or the button and close it if it did not, similar to this:
DEMO - Only hide if anything other than meny or button was clicked
The benefit here is that instead of having click events bound to multiple elements with stopPropagation
you have a single place to keep your logic.
In addition any functionality which relies on the click to bubble throug stays intact as you only inspect the source of the click in a focused scope which requires you to differentiate it.
Code from DEMO:
$('html').click(function(event) {
var $menu = $(".menu");
var $button = $("#open");
if(event.target !== $menu[0] && event.target !== $button[0]){
// add code here to close your menu...
$(".menu").hide(); // or similar code
}
});
$('#open').click(function(event) {
$(".menu").show();
});
In most cases where you only have 1 other click, stopPropagation
is great but in your case where you need more control I believe insepcting the source might be a better choice.
Off course, binding a click event with stopPropagation
to all other elements instead would propably work as well.