Last active
November 17, 2017 10:03
-
-
Save bittu/15655e3155adf5497a11fceff0bdc3b6 to your computer and use it in GitHub Desktop.
Scroll any element horizontally with smooth animation without any library.
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
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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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')})