jQuery bind click *ANYTHING* but *ELEMENT*
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/
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
}
});
I've done it like this in the past:
jQuery("body").bind("click", function(e)
{
var obj = (e.target ? e.target : e.srcElement);
if (obj.tagName != 'div' && obj.id != 'special')
{
// Perform your click action.
return false;
}
});
This would only execute if you didn't click on div#special. Honestly there may be better ways to do it, but this has worked for me.