Last active
June 14, 2018 14:42
-
-
Save jeangontijo/e148502d57f6080ec5523190a602f5db to your computer and use it in GitHub Desktop.
Scroll to element
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
// <a href="#" onclick="doScrolling('#myID', 1500)"> | |
function getElementY(query) { | |
return window.pageYOffset + document.querySelector(query).getBoundingClientRect().top | |
} | |
function doScrolling(element, duration) { | |
var startingY = window.pageYOffset | |
var elementY = getElementY(element) | |
var targetY = document.body.scrollHeight - elementY < window.innerHeight ? document.body.scrollHeight - window.innerHeight : elementY | |
var diff = targetY - startingY | |
var easing = function (t) { | |
return t < .5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1 | |
} | |
var start | |
if (!diff) return | |
window.requestAnimationFrame(function step(timestamp) { | |
if (!start) start = timestamp | |
var time = timestamp - start | |
var percent = Math.min(time / duration, 1) | |
percent = easing(percent) | |
window.scrollTo(0, startingY + diff * percent) | |
if (time < duration) { | |
window.requestAnimationFrame(step) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment