Last active
November 6, 2019 19:01
-
-
Save Fabiantjoeaon/09993f0ac155f809850157c02cd0443e to your computer and use it in GitHub Desktop.
Vanilla JS (ES6) smooth scrolling w/ Easing functions
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 scrollToItemId = (containerId, srollToId) => { | |
const scrollContainer = document.getElementById(containerId); | |
const item = document.getElementById(scrollToId); | |
//with animation | |
const from = scrollContainer.scrollTop; | |
const by = item.offsetTop - scrollContainer.scrollTop; | |
if (from < item.offsetTop) { | |
if (item.offsetTop > scrollContainer.scrollHeight - scrollContainer.clientHeight) { | |
by = (scrollContainer.scrollHeight - scrollContainer.clientHeight) - scrollContainer.scrollTop; | |
} | |
} | |
const currentIteration = 0; | |
/** | |
* get total iterations | |
* 60 -> requestAnimationFrame 60/second | |
* second parameter -> time in seconds for the animation | |
**/ | |
const animIterations = Math.round(60 * 0.5); | |
(function scroll() { | |
const value = easeOutCubic(currentIteration, from, by, animIterations); | |
scrollContainer.scrollTop = value; | |
currentIteration++; | |
if (currentIteration < animIterations) { | |
requestAnimationFrame(scroll); | |
} | |
})(); | |
} | |
// TODO: Write easing class | |
const linearEase = (currentIteration, startValue, changeInValue, totalIterations) => { | |
return changeInValue * currentIteration / totalIterations + startValue; | |
} | |
const easeOutCubic = (currentIteration, startValue, changeInValue, totalIterations) => { | |
return changeInValue * (Math.pow(currentIteration / totalIterations - 1, 3) + 1) + startValue; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Couple of typos here and there; srollToId is missing a 'c' and assignments to constant variable