9

Possible Duplicate:
How to detect a click outside an element?

I have a drop down menu that appears on click. When the user clicks away from it, it disappears.

For the on click Im using:

$("#title").click(function() {
    dropdown_show(); 
);

But when the user clicks away, Im using:

$('body').click(function(e) {
    if ((!$(e.target).is('#title'))&&(!$(e.target).is('#dropdown'))) {
        dropdown_hide();
    }   
});

Is there a better way to know when a user clicks away without having to run an event every single time the user clicks on the body?

Community
  • 1
  • 1
supercoolville
  • 7,198
  • 18
  • 48
  • 64
  • 2
    Just fyi, `!$(e.target).is('#title')` is easier written as `e.target.id !== 'title'`. – Felix Kling Jan 02 '12 at 14:02
  • You may want to use `.one` instead of `.click` on your hide. You attach it in the show and can then use a captured variable to determine if you're still inside or not instead of running selectors again. – Marc Jan 02 '12 at 14:08

2 Answers2

6

You could perhaps use the focus event, So if its not in focus you hide it. Here is jquery's api for it

Marthin
  • 6,009
  • 14
  • 53
  • 91
0

You could only set the body click event inside the menu click event, and use .unbind to remove the body click event when it gets clicked.

You might want to use .bind with a namespace: Best way to remove an event handler in jQuery?

Community
  • 1
  • 1
Spacedman
  • 86,225
  • 12
  • 117
  • 197