JavaScript repeat action when mouse held down




while mouse is down javascript (4)

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.

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.


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>

I see a problem with both solutions listed above.

onmouseup is only triggered if the mouse is released while it is over the button. If the user keeps the mouse down then moves the mouse away before releasing it then clearInterval is never fired and so do_something will fire forever.

You would need to add another event, "onmouseout", that also calls clearInterval.


var intervalId;
$("#button").mousedown(function() {
  intervalId = setInterval(do_something, 500);
}).mouseup(function() {
  clearInterval(intervalId);
}).mouseleave(function() {
//this should help solve the problem that occurs when the mouse leaves the button while pressed down
  clearInterval(intervalId);
});

function do_something() {
  // whatever
}




jquery