jrummell
jrummell

Reputation: 43087

Execute button event handler the entire time mouse button is depressed

I'd like to create a javascript mousedown event handler for a button. While the button is depressed, I need the handler to execute repeatedly until the button is released (mouseup is fired). E.g. holding an Up button should cause a text box value to increment until it is released.

What's the best way to handle this?

Upvotes: 1

Views: 199

Answers (1)

pimvdb
pimvdb

Reputation: 154868

You can make use of setInterval: http://jsfiddle.net/5wypC/1/.

var interval = null;
var i = 0;

$('button').mousedown(function() {
    clearInterval(interval); // Make sure to clear any intervals
                             // that are occasionally still running
    interval = setInterval(function() {
        $('textarea').val(i++);
    }, 100);
});

$('button').mouseup(function() {
    clearInterval(interval);
});

Upvotes: 5

Related Questions