Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if mousedown with an if statement?

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.

like image 281
android.nick Avatar asked Oct 08 '11 22:10

android.nick


2 Answers

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.

like image 75
James Allardice Avatar answered Sep 25 '22 10:09

James Allardice


Answering your original question, yes this is possible. When the mousedown event fires over an element the element becomes active and is selectable by the pseudo selector :active. In jQuery if nothing is selected an empty array is returned, we can use this to our advantage in combination with the .length array property and turn the active pseudo selector into a check to see if the mouse is down over a particular element or not like so:

if ( $('#id:active').length ) {
  //do something
}

Checking if the mouse was down over a particular element at a given point in time is a different event and does not go with the title of this question and should be changed might I add. Google brought me here and this answer is for those that will inevitably follow.

like image 34
Joshua Robinson Avatar answered Sep 23 '22 10:09

Joshua Robinson