Skip to content

Instantly share code, notes, and snippets.

@jljorgenson18
Last active August 29, 2015 14:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jljorgenson18/d05d21e034de987e569a to your computer and use it in GitHub Desktop.
Save jljorgenson18/d05d21e034de987e569a to your computer and use it in GitHub Desktop.
Finds an element using an id or a css class and smoothly scrolls to that element. Duration of the animation depends on scroll position. Based off of a stackoverflow answer by bfred.it at http://stackoverflow.com/questions/21474678/scrolltop-animation-without-jquery . NOTE: This only works for scrolling "up" to an element at the moment. The extra…
var scrollTo = function(id, cls, offset) {
var ele;
var targetOffset = 0;
var targetTop = 0;
if(offset) {
targetOffset = offset;
}
if(id) {
ele = document.getElementById(id);
} else if(cls) {
ele = document.getElementsByClassName(cls)[0];
}
if(ele) {
targetTop = -ele.getBoundingClientRect().top + targetOffset;
}
var scrollHeight = window.scrollY;
var targetY = scrollHeight - targetTop;
// The sqrt is to move the duration closer to 1000ms
var scrollStep = Math.PI / ((Math.sqrt(targetTop / 1000) * 1000) / 15);
var cosParameter = targetTop / 2;
var scrollCount = 0;
var scrollMargin;
window.requestAnimationFrame(step);
function step() {
setTimeout(function() {
if(window.scrollY > targetY) {
requestAnimationFrame(step);
scrollCount = scrollCount + 1;
scrollMargin = cosParameter - cosParameter * Math.cos(scrollCount * scrollStep);
window.scrollTo(0, (scrollHeight - scrollMargin));
}
}, 5);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment