Skip to content

Instantly share code, notes, and snippets.

@andreasmischke
Last active October 14, 2017 13:37
Show Gist options
  • Save andreasmischke/4963d1a5a93eac255e93d928dcd460a5 to your computer and use it in GitHub Desktop.
Save andreasmischke/4963d1a5a93eac255e93d928dcd460a5 to your computer and use it in GitHub Desktop.
Drag scrolling with right mouse button (disable contextmenu, but only if scrolled)
// ==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.0;
const BUTTON = 3; // 1 = left, 2 = middle, 3 = right mouse button
const CTRL_KEY = false;
const ALT_KEY = false;
const SHIFT_KEY = false;
const META_KEY = false;
const AUXCLICK = false;
let el, clientX, clientY;
let moved;
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);
moved = true;
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);
};
let preventContextMenu = e => {
if(moved) swallow(e);
};
if (!AUXCLICK) {
document.addEventListener('auxclick', e => {
if (!validEvent(e)) {
return;
}
swallow(e);
});
}
document.addEventListener('mousedown', e => {
if (!validEvent(e)) {
return;
}
swallow(e);
moved = false;
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);
if (BUTTON === 3) {
document.addEventListener('contextmenu', preventContextMenu, true);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment