1

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

I have an element on page say "myDiv" Using jQuery, how do I fire an event which would track a "tap" on any other area apart from "myDiv"

I am saying "tap" as I want to test it on iPad...You can even assume a normal "click" event instead of "tap"...Point is it should be "outside" of "myDiv"

Community
  • 1
  • 1
Diana
  • 435
  • 1
  • 11
  • 19

3 Answers3

0

An event on the tag should do it.

$("html").click(function(e) {
    alert("Test");
});

Example: http://jsfiddle.net/HenryGarle/HWApM/

Depending on your needs you could use the not selector:

$("div:not(div#winner)").live('click', function(e) {
    alert("Test");
});

Example: http://jsfiddle.net/HenryGarle/HWApM/1/

Or if its a nested div:

$("html").click(function(e) {
    alert("Test");
});

$("#winner").live('click', function(e) {
     e.stopPropagation(); 
});

Example: http://jsfiddle.net/HenryGarle/HWApM/2/

Henry
  • 2,187
  • 1
  • 15
  • 28
  • Why would you use `live` for the `html` tag? – Felix Kling Aug 09 '11 at 10:21
  • live is only necessary when the content you are trying to handle is generated after the point at which you are defining the event handler. However, it can (in certain circumstances) be more efficient. I probably wouldn't use it here unless you have a good reason. – Spycho Aug 09 '11 at 10:29
  • I think @Henry's last solution is more flexible and appropriate than the not selector. I also stopped propagation in my solution. – Spycho Aug 09 '11 at 10:30
  • I was using live because I was doing it in an ajax test site I have running. So in the case of me writing it, it was required. – Henry Aug 09 '11 at 10:38
0

Try binding a click handler to the body element and another click handler to myDiv which stops propagation of the click event. Here's a jsFiddle demonstrating the concept.

Spycho
  • 7,698
  • 3
  • 34
  • 55
-1

With the following you can register what you want to do when you click any area

$(document).click(function() {
  //your code here
});

And after that you just remove the callback from your div.

$("#myDiv").unbind("click");

This should work.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
lamelas
  • 872
  • 6
  • 15