0

The question is probably worded in a very confusing way so here's a quick example http://www.andytimney.com/projects/jquerydropdown/ if you click an "Archive", a dropdown will appear. Now if you want to close it, you need to click "Archive" again. However I want to close it by any click that doesn't target "Option 1", "Option 2". Similar to how Facebook does it if you click the "Account" menu in the top right corner.

The only solution that comes to my mind is to tie an onClick function to either or if that won't work to all elements present on the page except several elements that I'll specify. This solution looks a little hackish to me so I wonder if there is a smarter solution that I am missing.

Jacob
  • 77,566
  • 24
  • 149
  • 228
Eugene
  • 4,197
  • 7
  • 37
  • 54

3 Answers3

2

Read this How do I detect a click outside an element?

Community
  • 1
  • 1
Peeter
  • 9,282
  • 5
  • 36
  • 53
2

Attach an click event to the body and test if the clicked item was not an option:

$('body').click( function(e) {
                if(!$(e.target).parents('.option').length && !$(e.target).hasClass('.option')) {
                    $('.archive').hide();
                }
            });
Robin W.
  • 231
  • 1
  • 4
  • Note: This doesn't use stopPropagation() - sometimes you still want the click event to bubble up the dom to trigger other event handlers if they exist for other reasons. – Robin W. Apr 13 '11 at 17:07
0

have you tried document click and stop propagation for the event when menu click is triggered? interesting article on event bubbling http://www.quirksmode.org/js/events_order.html

zudokod
  • 4,074
  • 2
  • 21
  • 24