Check if mousedown with an if statement?

android.nick picture android.nick · Oct 9, 2011 · Viewed 33.5k times · Source

Is it possible to do something like this:

if ($(this).mousedown() == true) {

I thought that would work but it doesn't.

Additional details: I'm trying to check if the mouse button is down when the mouse leaves a specific DIV, so if the person is holding the mouse button down while their mouse leaves the div, do this, otherwise do that.

Answer

James Allardice picture James Allardice · Oct 9, 2011

The easiest way I can think of is to bind mousedown and mouseup event listeners to the document and update a global variable accordingly. In the mouseout event of your element you can check the state of that variable and act as appropriate. (Note: this assumes that you don't care whether or not the mouse was pressed down while over the div or not... you'll have to clarify your question around that).

var down = false;
$(document).mousedown(function() {
    down = true;
}).mouseup(function() {
    down = false;  
});
$("#example").mouseout(function() {
    if(down) {
        console.log("down");  
    } 
    else {
        console.log("up");   
    }
});

Here's a working example of the above.