Last active
October 16, 2017 08:47
-
-
Save bittu/309e95bac7a4093b960e3b9ec2536006 to your computer and use it in GitHub Desktop.
Scroll document to any vertical position 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 scrollBodyTo = (to, duration = 400, callback) => { | |
const move = (amount) => { | |
document.documentElement.scrollTop = amount; | |
document.body.parentNode.scrollTop = amount; | |
document.body.scrollTop = amount; | |
} | |
const position = () => { | |
return document.documentElement.scrollTop || document.body.parentNode.scrollTop || document.body.scrollTop; | |
} | |
const getDocHeight = () => { | |
return Math.max( | |
document.body.scrollHeight, document.documentElement.scrollHeight, | |
document.body.offsetHeight, document.documentElement.offsetHeight, | |
document.body.clientHeight, document.documentElement.clientHeight | |
); | |
} | |
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); | |
} | |
if (position() >= getDocHeight()) { | |
move(getDocHeight()); | |
} | |
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 scrollBodyTo method with params
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
scrollBodyTo(400, 500, ()=>{console.log('scrolling animation finished')})