Skip to content

Instantly share code, notes, and snippets.

@Fabiantjoeaon
Last active November 6, 2019 19:01
Show Gist options
  • Save Fabiantjoeaon/09993f0ac155f809850157c02cd0443e to your computer and use it in GitHub Desktop.
Save Fabiantjoeaon/09993f0ac155f809850157c02cd0443e to your computer and use it in GitHub Desktop.
Vanilla JS (ES6) smooth scrolling w/ Easing functions
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;
}
@vercetti11
Copy link

Couple of typos here and there; srollToId is missing a 'c' and assignments to constant variable

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment