Skip to content

Instantly share code, notes, and snippets.

@dzava
Created June 1, 2017 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dzava/3128eb2c1a87845b092c058be81445a6 to your computer and use it in GitHub Desktop.
Save dzava/3128eb2c1a87845b092c058be81445a6 to your computer and use it in GitHub Desktop.
export function scrollOffset(el) {
const box = el.getBoundingClientRect();
const body = document.body;
const docEl = document.documentElement;
const scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop;
const scrollLeft = window.pageXOffset || docEl.scrollLeft || body.scrollLeft;
const clientTop = docEl.clientTop || body.clientTop || 0;
const clientLeft = docEl.clientLeft || body.clientLeft || 0;
const top = box.top + scrollTop - clientTop;
const left = box.left + scrollLeft - clientLeft;
return {top: Math.round(top), left: Math.round(left)};
}
export function scrollTo(el) {
let start = window.pageYOffset, end = scrollOffset(el).top,
current = start, direction = start > end ? -1 : 1,
distance = Math.abs(start - end),
step = Math.round(distance / 25);
if (distance < 100) {
window.scrollTo(0, end);
return;
}
const stepF = () => {
window.scrollTo(0, current);
current += step * direction;
if ((direction === 1 && current < end)
|| direction === -1 && current > end) {
window.requestAnimationFrame(stepF);
} else {
window.requestAnimationFrame(() => window.scrollTo(0, end));
}
};
window.requestAnimationFrame(stepF);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment