Created
May 2, 2017 10:24
-
-
Save kdzwinel/f1fd8268fdf32a041e43d96dc6c005c8 to your computer and use it in GitHub Desktop.
Scroll to element or scroll by value
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
let rafId; | |
function scrollToElement(el, offsetTop = 0) { | |
scrollByValue(el.getBoundingClientRect().top - offsetTop); | |
} | |
function scrollByValue(offsetTop = 0) { | |
if (offsetTop !== 0) { | |
if (rafId) { | |
cancelAnimationFrame(rafId); | |
} | |
rafId = requestAnimationFrame(scrollStep.bind(null, offsetTop)); | |
} | |
} | |
function scrollStep(totalDistance) { | |
const speed = 0.085; | |
const totalDistansAbs = Math.abs(totalDistance); | |
let stepSize = parseInt(speed * totalDistansAbs, 10); | |
if (stepSize < 4) { | |
stepSize = totalDistansAbs < 4 ? totalDistansAbs : 4; | |
} | |
if (totalDistance > 0) { | |
totalDistance -= stepSize; | |
window.scrollBy(0, stepSize); | |
} else { | |
totalDistance += stepSize; | |
window.scrollBy(0, -stepSize); | |
} | |
if (totalDistance !== 0) { | |
rafId = requestAnimationFrame(scrollStep.bind(null, totalDistance)); | |
} | |
} | |
export default { | |
scrollToElement, | |
scrollByValue | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment