Jquery: mousedown effect (while left click is held down)

Zebra picture Zebra · Oct 20, 2010 · Viewed 31.5k times · Source

I need a function that executes a function while a button is pressed and stops executing when the button is let go

$('#button').--while being held down--(function() {
     //execute continuously
}); 

Answer

Yi Jiang picture Yi Jiang · Oct 20, 2010

I believe something like this would work:

var timeout, clicker = $('#clicker');

clicker.mousedown(function(){
    timeout = setInterval(function(){
        // Do something continuously 
    }, 500);

    return false;
});

$(document).mouseup(function(){
    clearInterval(timeout);
    return false;
});

See this demo: http://jsfiddle.net/8FmRd/