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

32,763

Solution 1

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/

Solution 2

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.

Solution 3

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);
}

Solution 4

$.fn.click2=function(cb,interval){
   var timeout;
   if(!interval) interval=100;
   $(this).mousedown(function () { 
      var target=this;
       timeout = setInterval(function(){
          cb.apply(target);
       }, interval);

    return false;
   }).mouseup(function () {
      clearInterval(timeout);
      return false;
   }).mouseout(function () {
      clearInterval(timeout);
      return false;
   });
}
Share:
32,763
Zebra
Author by

Zebra

Updated on August 17, 2022

Comments

  • Zebra
    Zebra over 1 year

    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
    });