🏠 Home 

CKHoldClick

A simple library to let doms could be hold with mouse events.

This script should not be not be installed directly. It is a library for other scripts to include with the meta directive // @require https://update.greasyfork.org/scripts/428696/945692/CKHoldClick.js

  1. // ==UserScript==
  2. // @name CKHoldClick
  3. // @namespace holdclick.ckylin.site
  4. // @version 0.1
  5. // @author CKylinMC
  6. // @grant unsafeWindow
  7. // @require https://greasyfork.org/scripts/428695-ckeventemitter/code/CKEventEmitter.js?version=945691
  8. // @license GPLv3 License
  9. // ==/UserScript==
  10. class HoldClick {
  11. dom;
  12. emitter = new EventEmitter;
  13. downTime = 0;
  14. holdingTime = 250;
  15. mouseDown = false;
  16. constructor(dom, holdingTime = 250) {
  17. if (dom instanceof HTMLElement) {
  18. this.dom = dom;
  19. this.initListener();
  20. }
  21. this.holdingTime = holdingTime;
  22. }
  23. onclick(func) {
  24. this.emitter.on("click", func);
  25. return this;
  26. }
  27. onhold(func) {
  28. this.emitter.on("hold", func);
  29. return this;
  30. }
  31. onup(func) {
  32. this.emitter.on("up", func);
  33. return this;
  34. }
  35. offclick(func) {
  36. this.emitter.off("click", func);
  37. return this;
  38. }
  39. offhold(func) {
  40. this.emitter.off("hold", func);
  41. return this;
  42. }
  43. offup(func) {
  44. this.emitter.off("up", func);
  45. return this;
  46. }
  47. handleMouseDown(e) {
  48. e.preventDefault();
  49. this.mouseDown = true;
  50. this.downTime = (new Date()).getTime();
  51. setTimeout(() => {
  52. if (this.mouseDown) {
  53. console.log(this);
  54. this.mouseDown = false;
  55. this.downTime = 0;
  56. this.emitter.emit("hold", e);
  57. }
  58. }, this.holdingTime)
  59. }
  60. handleMouseUp(e) {
  61. e.preventDefault();
  62. if (this.mouseDown) {
  63. this.mouseDown = false;
  64. const currTime = (new Date).getTime();
  65. if ((currTime - this.downTime) >= this.holdingTime) {
  66. this.emitter.emit("hold", e);
  67. } else {
  68. this.emitter.emit("click", e);
  69. }
  70. this.downTime = 0;
  71. }
  72. this.emitter.emit("up", e);
  73. }
  74. handleMouseOut(e) {
  75. e.preventDefault();
  76. if (this.mouseDown) {
  77. this.mouseDown = false;
  78. this.downTime = 0;
  79. this.emitter.emit("click", e);
  80. }
  81. }
  82. initListener() {
  83. this.dom.addEventListener("mouseup", this.handleMouseUp.bind(this))
  84. this.dom.addEventListener("mousedown", this.handleMouseDown.bind(this))
  85. this.dom.addEventListener("mouseout", this.handleMouseOut.bind(this))
  86. }
  87. }