Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery continuous mousedown

I have the following code snippets

$(document).mousedown(function(event) {
    doSomething();
}

I can capture the mousedown event successfully.

I am trying to do the following:

  1. Capture the first mousedown event
  2. I want to detect if the user is still holding the mouse down so I can do something else.
like image 734
pion Avatar asked Feb 10 '11 18:02

pion


2 Answers

Something like

var mouseStillDown = false;

$(document).mousedown(function(event) {
    mouseStillDown = true;
    doSomething();
});

function doSomething() {
    if (!mouseStillDown) { return; } // we could have come back from
                                     // SetInterval and the mouse is no longer down
    // do something

    if (mouseStillDown) { setInterval("doSomething", 100); }
}

$(document).mouseup(function(event) {
    mouseStillDown = false;
});
like image 109
RichardTheKiwi Avatar answered Oct 19 '22 00:10

RichardTheKiwi


var int00; // declared here to make it visible to clearInterval.

$('#trigger').mousedown(function(){
    int00 = setInterval(function() { repeatingfunction(); }, 50);
}).mouseup(function() {
    clearInterval(int00);
});

function repeatingfunction() {
    // This will repeat //
}

You can also put a clearInterval on the mouseleave event.

like image 40
Janos Avatar answered Oct 19 '22 01:10

Janos