Search code examples
javascriptjqueryif-statementmousedown

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.


Solution

  • 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.