Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
element-scrollto.js
/**
Smoothly scroll an element into the browser viewport
@param element {HTMLElement} - the element that which should be scrolled into the viewport
@param duration {Integer} - # of milliseconds the animation should take to complete
*/
var scroll = function (selector, duration) {
var
offset = function(element) {
var top = 0, left = 0;
do {
top += element.offsetTop || 0;
left += element.offsetLeft || 0;
element = element.offsetParent;
} while(element);
return {
top: top,
left: left
};
},
startingY = window.pageYOffset,
diff = 0,
node = null,
start;
duration = ! duration ? 1000 : duration;
node = typeof arguments[0] == 'string' ? document.querySelector(arguments[0]) : arguments[0];
if (! node) {
throw new Error('Invalid node ' + selector);
}
diff = offset(node).top - startingY;
window.requestAnimationFrame(function step(timestamp) {
if (!start) {
start = timestamp;
}
var
time = timestamp - start, // elapsed miliseconds since start of scrolling.
percent = Math.min(time / duration, 1); // percent of completion in range [0, 1].
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
You can’t perform that action at this time.