Twitter Image Switch With Drag

Switch between previous and next images by dragging the mouse, click on the image to close it.

  1. // ==UserScript==
  2. // @name Twitter Image Switch With Drag
  3. // @name:ja Twitter Image Switch With Drag
  4. // @name:zh-CN Twitter 拖曳切换图像
  5. // @name:zh-TW Twitter 拖曳切換圖片
  6. // @description Switch between previous and next images by dragging the mouse, click on the image to close it.
  7. // @description:ja マウスをドラッグして前後の画像を切り替え、画像をクリックして閉じます。
  8. // @description:zh-cn 使用鼠标拖曳来切换上一张或下一张图像, 点击图像即可关闭图像
  9. // @description:zh-tw 使用滑鼠拖曳來切換上一張或下一張圖片, 點擊圖片即可關閉圖片
  10. // @namespace none
  11. // @version 0.1.9
  12. // @author ShanksSU
  13. // @match https://x.com/*
  14. // @match https://mobile.x.com/*
  15. // @icon https://www.google.com/s2/favicons?sz=64&domain=twitter.com
  16. // @grant GM_setValue
  17. // @grant GM_getValue
  18. // @grant GM_addStyle
  19. // @compatible Chrome
  20. // @license MIT
  21. // ==/UserScript==
  22. function ImageSwitchWithDrag() {
  23. function clickBtn(name) {
  24. const btn = document.querySelector(`div[aria-labelledby="modal-header"] button[aria-label*="${name}"]`);
  25. if (btn) {
  26. btn.click();
  27. return true;
  28. }
  29. return false;
  30. }
  31.  
  32. GM_addStyle('img { -webkit-user-drag: none; }');
  33.  
  34. window.addEventListener('wheel', function({ deltaY, target: { tagName, baseURI } }) {
  35. if (tagName == 'IMG' && /\/photo\//.test(baseURI)) {
  36. if (deltaY < 0) clickBtn('Previous slide');
  37. else if (deltaY > 0) clickBtn('Next slide');
  38. }
  39. });
  40.  
  41. let initialXCoordinate = 0;
  42. let clickCount = 0;
  43. const doubleClickThreshold = 300;
  44. window.addEventListener('mousedown', function({ clientX }) {
  45. initialXCoordinate = clientX;
  46. });
  47.  
  48. window.addEventListener(
  49. 'mouseup',
  50. function({ button, clientX, target: { tagName, baseURI }, timeStamp }) {
  51. if (button !== 0 || !(tagName == 'IMG' && /\/photo\//.test(baseURI))) return;
  52. const distanceMovedX = clientX - initialXCoordinate;
  53. clickCount++;
  54. setTimeout(() => {
  55. if (clickCount === 1) {
  56. if (Math.abs(distanceMovedX) === 0) {
  57. if (baseURI === window.location.href) {
  58. clickBtn('Close');
  59. }
  60. } else if (distanceMovedX > 0) {
  61. clickBtn('Previous slide');
  62. } else if (distanceMovedX < 0) {
  63. clickBtn('Next slide');
  64. }
  65. } else if (clickCount === 2) {
  66. clickBtn('Likes. Like');
  67. }
  68. clickCount = 0;
  69. }, doubleClickThreshold);
  70. }
  71. );
  72.  
  73. }
  74. ImageSwitchWithDrag();