views:

28

answers:

1

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
}); 
+5  A: 

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/J9QNZ/4

Yi Jiang
One problem - if you let go off of the hit area, the effect loops forever. You should probably look at having the `mouseup` function on the entire document, rather than just `clicker`.
Jeriko
@Jeriko You're right. I'm editing my answer now
Yi Jiang
Or instead of the setInterval solution he might want to use the mousemove event.
bazmegakapa
@baz Hmmm.. Unlikely, as *any* sort of mouse movement after the button is held would call `clearTimeout`, which generally speaking doesn't seem like the correct behavior here.
Yi Jiang
@Yi Jang: Excellent, thank you very much!!!
dany
@Jeriko: Thanks for the advice
dany
@yi There would be no timeout. On mousedown a class would be added to the element, and on mousemove the function would be executed (based on the class). Global mouseup would remove the class. I was thinking he is trying to do some kind of dragging.
bazmegakapa