Skip to content

Instantly share code, notes, and snippets.

@bittu
Last active November 17, 2017 10:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bittu/15655e3155adf5497a11fceff0bdc3b6 to your computer and use it in GitHub Desktop.
Save bittu/15655e3155adf5497a11fceff0bdc3b6 to your computer and use it in GitHub Desktop.
Scroll any element horizontally with smooth animation without any library.
const easeInQuad = (t, b, c, d) => {
return c * (t /= d) * t + b;
}
const requestAnimFrame = (() => {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 1000 / 60); };
})();
export const scrollElementLeftTo = (element, to, duration = 400, callback) => {
const move = (amount) => {
element.scrollLeft = amount;
}
const position = () => {
return element.scrollLeft;
}
const start = position();
const change = to - start;
const increment = 50;
let currentTime = 0;
const animateScroll = () => {
currentTime += increment;
/* You can use any easing function here */
let val = easeInQuad(currentTime, start, change, duration);
move(val);
if (currentTime < duration) {
requestAnimFrame(animateScroll, increment);
} else {
if (position() <= 0) {
move(0);
}
callback && typeof callback === 'function' && callback();
}
};
animateScroll();
}
@bittu
Copy link
Author

bittu commented Oct 16, 2017

Call scrollElementLeftTo method with params

element: element to scroll
to: position to scroll body
duration: optional duration in ms to animate scrolling (defaults: 400ms)
callback: optional callback to be called after animation is fininshed

scrollElementLeftTo (document.getElementById('carouselDiv'), 400, 500, ()=>{console.log('scrolling animation finished')})

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