Created
September 18, 2018 14:15
-
-
Save hideya/4a5afd09ae4e6888f7b463ceb5ed8e13 to your computer and use it in GitHub Desktop.
Smooth scroll to a specified DOM 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
// based on https://gist.github.com/andjosh/6764939 | |
function scrollToElem(target, duration) { | |
var start = window.pageYOffset; | |
var to = target.getBoundingClientRect().top; | |
var change = to - start; | |
var currentTime = 0; | |
var increment = 20; | |
function animateScroll(){ | |
currentTime += increment; | |
var val = easeInOutQuad(currentTime, start, change, duration); | |
window.scrollTo(window.pageXOffset, val); | |
if (currentTime < duration) { | |
setTimeout(animateScroll, increment); | |
} | |
}; | |
animateScroll(); | |
//t = current time | |
//b = start value | |
//c = change in value | |
//d = duration | |
function easeInOutQuad(t, b, c, d) { | |
t /= d/2; | |
if (t < 1) return c/2*t*t + b; | |
t--; | |
return -c/2 * (t*(t-2) - 1) + b; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment