Just thought I'd share this and see what kind of improvements could be made that I'm not aware of and taking advantage of.
The situation is this: I have a list of items on a page that have a button that opens a menu. I need a click away event as well as close others when a new menu is opened. Also some of the menu actions will replace items in the list which means I have new dynamic menu buttons on the page.
To do this efficiently (as far as I can tell) you need to use event delegation and it ends up looking like this:
$(document).delegate( '.button', 'click', function(e){
var $button = $(this);
var $menu = $button.closest('.menu');
e.stopPropagation();
// Close others
$('.button').each(function(){
$(this).closest('.menu').removeClass('open');
});
// Toggle target open/close
if( $menu.hasClass('open') ){
$menu.removeClass('open');
}
else{
$menu.addClass('open');
}
$(document).on('click', function(e){
var $target = $(e.target);
if( !$target.is( $( $menu.find('button') ) ) ){
if( $menu.hasClass('open') ){
$menu.removeClass('open');
}
}
});
});
Maybe there's a better way?