mousehold.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /**
  2. * jQuery mousehold plugin - fires an event while the mouse is clicked down.
  3. * Additionally, the function, when executed, is passed a single
  4. * argument representing the count of times the event has been fired during
  5. * this session of the mouse hold.
  6. *
  7. * @author Remy Sharp (leftlogic.com)
  8. * @date 2006-12-15
  9. * @example $("img").mousehold(200, function(i){ })
  10. * @desc Repeats firing the passed function while the mouse is clicked down
  11. *
  12. * @name mousehold
  13. * @type jQuery
  14. * @param Number timeout The frequency to repeat the event in milliseconds
  15. * @param Function fn A function to execute
  16. * @cat Plugin
  17. */
  18. jQuery.fn.mousehold = function(timeout, f) {
  19. if (timeout && typeof timeout == 'function') {
  20. f = timeout;
  21. timeout = 100;
  22. }
  23. if (f && typeof f == 'function') {
  24. var timer = 0;
  25. var fireStep = 0;
  26. return this.each(function() {
  27. jQuery(this).mousedown(function() {
  28. fireStep = 1;
  29. var ctr = 0;
  30. var t = this;
  31. timer = setInterval(function() {
  32. ctr++;
  33. f.call(t, ctr);
  34. fireStep = 2;
  35. }, timeout);
  36. })
  37. clearMousehold = function() {
  38. clearInterval(timer);
  39. if (fireStep == 1) f.call(this, 1);
  40. fireStep = 0;
  41. }
  42. jQuery(this).mouseout(clearMousehold);
  43. jQuery(this).mouseup(clearMousehold);
  44. })
  45. }
  46. }