Skip to content

Instantly share code, notes, and snippets.

@hideya
Created September 18, 2018 14:15
Show Gist options
  • Save hideya/4a5afd09ae4e6888f7b463ceb5ed8e13 to your computer and use it in GitHub Desktop.
Save hideya/4a5afd09ae4e6888f7b463ceb5ed8e13 to your computer and use it in GitHub Desktop.
Smooth scroll to a specified DOM element
// 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