Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery bind click *ANYTHING* but *ELEMENT*

Tags:

jquery

click

Say there are some elements floating around, and I'm trying to do some when I click ANYTHING(divs, body, whatever...) but the one specified (e.g. div#special).

I'm wondering if there's a better way to achieve this besides the following method I can think of...

$(document).bind('click', function(e) {     get mouse position x, y     get the element (div#special in this case) position x, y     get the element width and height     determine if the mouse is inside the element     if(inside)         do nothing     else         do something }); 
like image 444
railOne Avatar asked Jul 09 '11 15:07

railOne


2 Answers

To handle the "do this except when this element is clicked" situation, the general approach is to add an event handler to the document which handles the "do this" case, then add another event handler to the "except this" element, which simply prevents the click event bubbling up to the document;

$('#special').on('click', function(e) {     e.stopPropagation(); });  $(document).on('click', function (e) {  // Do whatever you want; the event that'd fire if the "special" element has been clicked on has been cancelled. }); 

See the event.stopPropagation() documentation. For those of you using versions earlier than jQuery 1.7 (as was the case when this question was asked), you won't be able to use on(); instead simple replace the 2 uses of on() with bind(); the signature in this case is the same.

Demo here; http://jsfiddle.net/HBbVC/

like image 59
Matt Avatar answered Sep 21 '22 22:09

Matt


You could also do

$(document).bind('click', function(e) {   if(!$(e.target).is('#special')) {     // do something   } }); 

or if div#special has child elements you could do

$(document).bind('click', function(e) {   if($(e.target).closest('#special').length === 0) {     // do something   } }); 
like image 20
bmavity Avatar answered Sep 17 '22 22:09

bmavity