Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript repeat action when mouse held down

Is there to have a JavaScript function repeated every so many milliseconds that an html button is held down? It would be great if this could be done with standard JavaScript, but using jQuery or a jQuery plugin would be great too.

like image 980
Brian Avatar asked Dec 20 '09 05:12

Brian


2 Answers

On the mousedown() event, this code starts a repeating timer (every 500ms in this example) that is cancelled as soon as the mouseup() event occurs. This should be adaptable to what you want:

var intervalId;
$("#button").mousedown(function() {
  intervalId = setInterval(do_something, 500);
}).mouseup(function() {
  clearInterval(intervalId);
});

function do_something() {
  // whatever
}

See setInterval() for more information on clearing timers.

like image 181
cletus Avatar answered Nov 13 '22 07:11

cletus


I would use the javascript function setInterval() within a function that gets called on mouse down.

<input type="button" id="button" onmousedown="inter=setInterval(startAction, 1*1000);"
onmouseup="clearInterval(inter);" value="click here" />

<script type="text/javascript">
    function startAction(){
        //whatever you want done
    }
</script>
like image 24
munch Avatar answered Nov 13 '22 07:11

munch