Skip to content

Instantly share code, notes, and snippets.

@cyyyu
Last active June 20, 2020 17:02
Show Gist options
  • Save cyyyu/ed564c59e26ef480df887813fd65dddd to your computer and use it in GitHub Desktop.
Save cyyyu/ed564c59e26ef480df887813fd65dddd to your computer and use it in GitHub Desktop.
back-to-top greasyfork script
// ==UserScript==
// @name Back to top
// @namespace cyyyu
// @version 0.3
// @description scroll to top
// @author Chuang Yu
// @match https://*/*
// @grant none
// @run-at document-end
// ==/UserScript==
(function() {
'use strict';
/* written in es5 */
var rootNode = document.querySelector("html")
var prevLocations = new Map() // node: number
var timers = new Map() // node: number
var backToPrevLocationDelay = 10000 // 10s
rootNode.addEventListener("dblclick", function (evt) {
var path = evt.path
for (var i = 0; i < path.length; i++) {
var node = path[i]
if (!isScrollable(node)) continue;
if (!evt.altKey) return
if (!isAtTop(node)) {
clearTimeout(timers.get(node))
scrollTo(node, 0)
} else if (prevLocations.has(node)) {
scrollTo(node, prevLocations.get(node))
}
}
})
function isAtTop(node) {
return node.scrollTop === 0
}
function scrollTo(node, top) {
var prevScrollBehavior = node.style.scrollBehavior
var prevLocation = node.scrollTop
node.style.scrollBehavior = "smooth"
node.scrollTop = top
node.style.scrollBehavior = prevScrollBehavior
if (top === 0) {
prevLocations.set(node, prevLocation)
var timer = setTimeout(
function () { prevLocations.delete(node) },
backToPrevLocationDelay
)
timers.set(node, timer)
}
}
function isScrollable(node) {
return (
(node.scrollHeight - node.clientHeight > 100) &&
(node.clientHeight > 50)
)
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment