scroll_to_top

scroll to top for PC and mobile

  1. // ==UserScript==
  2. // @name scroll_to_top
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.1.7
  5. // @description scroll to top for PC and mobile
  6. // @author amormaid
  7. // @run-at document-end
  8. // @match http(s)?://*/*
  9. // @include http://*
  10. // @include https://*
  11. // @icon https://www.google.com/s2/favicons?sz=64&domain=tampermonkey.net
  12. // @grant none
  13. // @license MIT
  14. // ==/UserScript==
  15.  
  16. (function() {
  17. 'use strict';
  18.  
  19. const sttClassName = 'scroll-to-top';
  20. let timeoutID;
  21.  
  22. function scroll_or_touchmove_handler() {
  23. clearTimeout(timeoutID);
  24. const btn = (document.getElementsByClassName(sttClassName) || [])[0];
  25. if (btn && btn.style.cssText !== 'opacity: 1;') {
  26. btn.style.cssText = 'opacity: 1;';
  27. }
  28. timeoutID = setTimeout(() => {
  29. btn.style.cssText = 'opacity: .1;';
  30. timeoutID = null;
  31. }, 5000);
  32. }
  33.  
  34. function addCSSStyle() {
  35. var cssStyle = document.createElement('style');
  36. cssStyle.type = 'text/css';
  37. cssStyle.textContent = [
  38. '.' + sttClassName + ' {',
  39. ' width: 10vw;',
  40. ' height: 10vw;',
  41. ' line-height: 10vw;',
  42. ' text-align: center;',
  43. ' background: whiteSmoke;',
  44. ' font-weight: bold;',
  45. ' font-size: 6vw;',
  46. ' color: #444;',
  47. ' text-decoration: none;',
  48. ' position: fixed;',
  49. ' bottom: 0;',
  50. ' left: 0;',
  51. ' display: block;',
  52. ' border: 1px solid grey;',
  53. ' border-top-right-radius: 5vw;',
  54. ' box-shadow: 0 0 3px grey;',
  55. ' transition: opacity 250ms ease-out;',
  56. ' z-index: 1000;',
  57. ' cursor: pointer;',
  58. '}'
  59. ].join('\n');
  60. if(document.head) {
  61. document.head.appendChild(cssStyle);
  62. }
  63. }
  64.  
  65. (() => {
  66. if ('ontouchstart' in window) {
  67. window.ontouchmove = scroll_or_touchmove_handler;
  68. } else {
  69. window.onscroll = scroll_or_touchmove_handler;
  70. window.onwheel = function() {
  71. if(typeof timeoutID != 'number') {
  72. return;
  73. }
  74. clearTimeout(timeoutID);
  75. timeoutID = null;
  76. };
  77.  
  78. }
  79. addCSSStyle();
  80. var div = document.createElement('div');
  81. div.className = sttClassName;
  82. div.textContent = '⇧';
  83. div.style.cssText = 'opacity: .1;';
  84. div.onclick = () => window.scrollTo(0, 0);
  85. document.body.appendChild(div);
  86.  
  87.  
  88. })();
  89.  
  90. })();