Instantly share code, notes, and snippets.

Embed
What would you like to do?
Drag scrolling with middle-mouse button
// ==UserScript==
// @name Hand Scroll
// @namespace https://gavinhungry.io
// @version 1.5.0
// @description Drag scrolling with mouse movement
// @author Gavin Lloyd <gavinhungry@gmail.com>
// @include *
// @grant none
// ==/UserScript==
(() => {
'use strict';
const SCALE_X = 0.0;
const SCALE_Y = 1.5;
const BUTTON = 2;
const CTRL_KEY = false;
const ALT_KEY = false;
const SHIFT_KEY = false;
const META_KEY = false;
const AUXCLICK = false;
let el, clientX, clientY;
let validEvent = e =>
e.which === BUTTON &&
e.ctrlKey === CTRL_KEY &&
e.altKey === ALT_KEY &&
e.shiftKey === SHIFT_KEY &&
e.metaKey === META_KEY;
let getScrollableEl = el => {
try {
let overflowY = window.getComputedStyle(el).overflowY;
return overflowY !== 'visible' && overflowY !== 'hidden' &&
el !== document.body &&
el.scrollHeight > el.clientHeight ?
el : getScrollableEl(el.parentNode);
} catch(err) {
return window;
}
};
let mousemove = e => {
swallow(e);
el.scrollBy(SCALE_X * (clientX - e.clientX), SCALE_Y * (clientY - e.clientY));
clientX = e.clientX;
clientY = e.clientY;
};
let swallow = e => {
e.preventDefault();
e.stopPropagation();
};
let finish = e => {
swallow(e);
document.removeEventListener('mousemove', mousemove, true);
document.removeEventListener('mouseover', swallow, true);
document.removeEventListener('mouseenter', swallow, true);
document.removeEventListener('mouseup', finish, true);
};
if (!AUXCLICK) {
document.addEventListener('auxclick', e => {
if (!validEvent(e)) {
return;
}
swallow(e);
});
}
document.addEventListener('mousedown', e => {
if (!validEvent(e)) {
return;
}
swallow(e);
el = getScrollableEl(e.target);
clientX = e.clientX;
clientY = e.clientY;
document.addEventListener('mousemove', mousemove, true);
document.addEventListener('mouseover', swallow, true);
document.addEventListener('mouseenter', swallow, true);
document.addEventListener('mouseup', finish, true);
}, true);
})();
@andreasmischke

This comment has been minimized.

andreasmischke commented Oct 14, 2017

Thanks for the great work! That totally replaces the broken HandTool extension for me!

Since I used the right mouse button until now, it was a bit annoying that the context menu popped up all the time.
I forked your Gist and added a few lines that prevent the context menu. But only if it there was any move mousement (= scrolling) after the click. That way the context menu still remains usable (if you have a steady hand)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment