Created
September 5, 2019 05:13
-
-
Save chardos/cbaa1d370b3e7c96025d34be6e7e5ab9 to your computer and use it in GitHub Desktop.
Smooth scrolling
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
const easeModifier = (t) => { | |
return t > 0.5 ? 4 * Math.pow(t - 1, 3) + 1 : 4 * Math.pow(t, 3); | |
} | |
const createPositionsArray = (numFrames, totalDistance, pagePosition) => { | |
return new Array(numFrames + 1).fill(null).map((x, i) => { | |
const progress = i / numFrames; | |
const incrementDistance = easeModifier(progress) * totalDistance; | |
return pagePosition + (incrementDistance); | |
}) | |
} | |
const recurser = (positions) => { | |
if (positions.length) { | |
const [position, ...rest] = positions; | |
window.scrollTo(0, position); | |
requestAnimationFrame(() => {recurser(rest)}) | |
} | |
} | |
function scrollToElement ({ element, offset = 0, duration = 300 }) { | |
const pagePosition = window.pageYOffset; | |
const elementOffset = element.getBoundingClientRect().top; | |
const totalDistance = elementOffset + offset; | |
const numFrames = Math.ceil(duration / 16.6); | |
const positions = createPositionsArray(numFrames, totalDistance, pagePosition) | |
recurser(positions); | |
} | |
export default scrollToElement; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment