Last active
June 27, 2020 04:52
-
-
Save macu/10e0b884f8c92d557409dea7fa6c8934 to your computer and use it in GitHub Desktop.
Utility method to scroll the viewport when the mouse approaches the top or bottom edge, for example while dragging items vertically
This file contains hidden or 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
// Call when dragging starts, returns handler. | |
// Call handler.stop() when dragging stops. | |
export function startAutoscroll() { | |
const GUTTER_SIZE = 70; // distance from edge of viewport where scrolling starts | |
const SCALE_RANGE = 8; // higher value gives potential for faster scrolling | |
const $window = $(window); | |
let requestId = null; | |
let clientY = null; // cursor position within viewport | |
function handleMouseMove(e) { | |
clientY = e.clientY; | |
} | |
$window.on('mousemove', handleMouseMove); | |
function handleScroll() { | |
if (clientY !== null) { | |
let viewportHeight = $window.height(), delta = 0; | |
if (clientY < GUTTER_SIZE) { // Scroll up | |
let factor = (GUTTER_SIZE - clientY) / GUTTER_SIZE; | |
delta = -((factor * SCALE_RANGE) + 1); | |
} else if (clientY > (viewportHeight - GUTTER_SIZE)) { // Scroll down | |
let factor = (clientY - (viewportHeight - GUTTER_SIZE)) / GUTTER_SIZE; | |
delta = (factor * SCALE_RANGE) + 1; | |
} | |
if (delta !== 0) { | |
$window.scrollTop($window.scrollTop() + delta); | |
} | |
} | |
console.log('requesting'); | |
requestId = window.requestAnimationFrame(handleScroll); | |
} | |
requestId = window.requestAnimationFrame(handleScroll); | |
return { | |
stop: function() { | |
$window.off('mousemove', handleMouseMove); | |
if (requestId) { | |
window.cancelAnimationFrame(requestId); | |
requestId = null; | |
} | |
}, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment