Szaman
Szaman

Reputation: 2398

jQuery: How to detect if mouse click location is outside of a div

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

Answers (5)

Milind Anantwar
Milind Anantwar

Reputation: 82241

You can use:

$(document).mousedown(function(event) {
 var specificDiv= $("#specificDiv");
 if (specificDiv.is(event.target))
   console.log("you clicked specificDiv.");
});

Upvotes: 7

SharpEdge
SharpEdge

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

alexP
alexP

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

Alexander Bondar
Alexander Bondar

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

AmmarCSE
AmmarCSE

Reputation: 30607

$(document).mousedown(function() {
    if($(this).closest('#specificDiv').length == 0){
    }
});

Upvotes: 0

Related Questions