UNPKG

svelte-scrolling

Version:

Scroll to given elements with smooth animation

27 lines (26 loc) 1.06 kB
const currentPosition = (start, end, elapsed, duration, easing) => { if (elapsed > duration) return end; return start + (end - start) * easing(elapsed / duration); }; const smoothScroll = async (options, callback) => { return new Promise((resolve) => { const { start, end, duration, easing } = options; const clock = Date.now(); let step = () => { const elapsed = Date.now() - clock; const positionX = currentPosition(start.x, end.x, elapsed, duration, easing); const positionY = currentPosition(start.y, end.y, elapsed, duration, easing); callback({ x: positionX, y: positionY }); if (elapsed > duration) return resolve(); window.requestAnimationFrame(step); }; window.addEventListener('wheel', function stopAnimation() { step = () => { }; window.removeEventListener('wheel', stopAnimation); }); window.requestAnimationFrame(step); }); }; export default smoothScroll;