I'm trying to set conditions on a jQuery event. I have an input element and a div. I want to detect a click anywhere on the page and to execute that method but only if the click is not on the input or div.
Use the jQuery click() or live() functions and then check the target of the click event using the jQuery is() function.
.
$(document.body).click(function(e) {
if( !$(e.target).is("input, div") ) {
console.log("Run function because image or div were not clicked!");
}
});
Example webpage => http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-document-click-exclusion.html
Example firebug output after clicking around on example page
Something like this should work.
$('body').click(function(event){ // body click
var $target = $(event.target); // click target
if($target.is('#mydiv, #myinput')) { // click target is div or input
$target.click(); // click div or input
}
});
Basically assign a click handler to the body of the page, then test the target Element of the event to see if the id of that target element matches your div or your input.
$("body").click(function(evt) {
var targetElementId = evt.target.id;
if (!(targetElementId == "yourDivID" || targetElementId == "yourinputId"))
{
// your event code here.
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With