Skip to content

Instantly share code, notes, and snippets.

@cyrusfirheir
Created August 18, 2021 14:40
Show Gist options
  • Save cyrusfirheir/e9fab07845cec804c0ea7ee1362f6397 to your computer and use it in GitHub Desktop.
Save cyrusfirheir/e9fab07845cec804c0ea7ee1362f6397 to your computer and use it in GitHub Desktop.
Drag element to scroll
(function () {
"use strict";
jQuery.fn.extend({
dragToScroll({ horizontal = true, vertical = true } = {}) {
const position = { top: 0, left: 0, x: 0, y: 0 };
const element = this.get(0);
function downHandler({ clientX, clientY }) {
Object.assign(position, {
top: element.scrollTop,
left: element.scrollLeft,
x: clientX,
y: clientY
});
$(document)
.on("mousemove.drag-to-scroll", moveHandler)
.one("mouseup blur", upHandler);
}
function moveHandler({ clientX, clientY }) {
if (horizontal) {
const dx = clientX - position.x;
element.scrollLeft = position.left - dx;
}
if (vertical) {
const dy = clientY - position.y;
element.scrollTop = position.top - dy;
}
}
function upHandler() {
$(document).off(".drag-to-scroll");
}
this.on("mousedown", downHandler);
return this;
}
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment