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

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


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/


A small modification to the original answer:

$('#Clicker').mousedown(function () {    //do something here    timeout = setInterval(function () {        //do same thing here again    }, 500);    return false;});$('#Clicker').mouseup(function () {    clearInterval(timeout);    return false;});$('#Clicker').mouseout(function () {    clearInterval(timeout);    return false;});

With the mouseout event on the Clicker it stops when you move your mouse out of the click area.

The reason why I suggest to do the same thing twice is to get a smoother effect. If you don't do it once before the timeout is set it will be a delay of, in this case, 500ms before something happens.


Here's a pure JavaScript implementation of the supplied solutions which has extended support for touch screens. You supply the id, action to perform (function(){}) and the interval (ms) to repeat the action. Note that this implementation will also execute the action immediately, rather than waiting for the interval to lapse.

// Configures an element to execute a function periodically whilst it holds the user's attention via a mouse press and hold.function assertPeriodicPress(id, action, interval) {  // Listen for the MouseDown event.  document.getElementById(id).addEventListener('mousedown', function(ev) { action(); timeout = setInterval(action, interval); return false; }, false);  // Listen for mouse up events.  document.getElementById(id).addEventListener('mouseup', function(ev) { clearInterval(timeout); return false; }, false);  // Listen out for touch end events.  document.getElementById(id).addEventListener('touchend', function(ev) { clearInterval(timeout); return false; }, false);}