Skip to content

Instantly share code, notes, and snippets.

@wp-kitten
Created October 7, 2018 13:32
Show Gist options
  • Save wp-kitten/8a9ffe32e6f95009e704db7bf4ec128d to your computer and use it in GitHub Desktop.
Save wp-kitten/8a9ffe32e6f95009e704db7bf4ec128d to your computer and use it in GitHub Desktop.
/*
usage: scrollToElm($containerElement.get(0), $targetItem.get(0), 0.2);
url: https://stackoverflow.com/a/51005649
*/
function scrollToElm(container, elm, duration) {
var pos = getRelativePos(elm);
scrollTo(container, pos.top, duration); // duration in seconds
}
function getRelativePos(elm) {
var pPos = elm.parentNode.getBoundingClientRect(), // parent pos
cPos = elm.getBoundingClientRect(), // target pos
pos = {};
pos.top = cPos.top - pPos.top + elm.parentNode.scrollTop;
pos.right = cPos.right - pPos.right;
pos.bottom = cPos.bottom - pPos.bottom;
pos.left = cPos.left - pPos.left;
return pos;
}
function scrollTo(element, to, duration, onDone) {
var start = element.scrollTop,
change = to - start,
startTime = performance.now(),
val, now, elapsed, t;
function animateScroll() {
now = performance.now();
elapsed = (now - startTime) / 1000;
t = (elapsed / duration);
element.scrollTop = start + change * easeInOutQuad(t);
if (t < 1)
window.requestAnimationFrame(animateScroll);
else
onDone && onDone();
};
animateScroll();
}
function easeInOutQuad(t) {
return t < .5 ? 2 * t * t : -1 + (4-2 * t) * t
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment