Created
April 27, 2017 16:48
-
-
Save davidfmiller/f88c6fda94d125278d27a33d53f69a07 to your computer and use it in GitHub Desktop.
element-scrollto.js
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
/** | |
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