Reputation: 2398
I have this code which detects any mouse click on a website:
$(document).mousedown(function() {
console.log("you clicked somewhere.");
});
How do I make it to only trigger an action if the clicked location is outside of #specificDiv
?
Upvotes: 1
Views: 1381
Reputation: 82241
You can use:
$(document).mousedown(function(event) {
var specificDiv= $("#specificDiv");
if (specificDiv.is(event.target))
console.log("you clicked specificDiv.");
});
Upvotes: 7
Reputation: 1762
Use the target
property of the event object.
target
points to the element on which the event generated
var myDiv = $("#myDiv");
$(document).mousedown(function(ev) {
if(myDiv.is(ev.target)){
console.log("you clicked on myDiv.");
}else{
console.log("you clicked somewhere.");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv" style="height:100px; width:100px; background-color:#00FF00;" ></div>
Upvotes: 0
Reputation: 3765
$('#your_div').mousedown(function(e){
e.stopPropagation(); //Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
});
$(document).mousedown(function(e){
console.log("you clicked somewhere.");
});
Upvotes: -1
Reputation: 534
This should help you:
$(document).mousedown(function (ev) {
var $target = $(ev.target);
var $specificDiv = $target.closest('#specificDiv');
if (!$specificDiv || !$specificDiv.length) {
// clicked location is outside
}
});
Upvotes: 0
Reputation: 30607
$(document).mousedown(function() {
if($(this).closest('#specificDiv').length == 0){
}
});
Upvotes: 0