Created
August 18, 2021 14:40
-
-
Save cyrusfirheir/e9fab07845cec804c0ea7ee1362f6397 to your computer and use it in GitHub Desktop.
Drag element to scroll
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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