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
?
You can use:
$(document).mousedown(function(event) {
var specificDiv= $("#specificDiv");
if (specificDiv.is(event.target))
console.log("you clicked specificDiv.");
});
$(document).mousedown(function() {
if($(this).closest('#specificDiv').length == 0){
}
});
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>
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
}
});
$('#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.");
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.