Skip to content

Instantly share code, notes, and snippets.

@moeamaya
Last active February 23, 2021 15:06
Show Gist options
  • Save moeamaya/6995c83651cba2cf7416 to your computer and use it in GitHub Desktop.
Save moeamaya/6995c83651cba2cf7416 to your computer and use it in GitHub Desktop.
// Get element offset from top of page
function getOffset(el) {
el = el.getBoundingClientRect();
return {
left: el.left + window.scrollX,
top: el.top + window.scrollY
};
};
// Scroll element to a integer position
function scrollTo(element, to, duration) {
if (duration <= 0) return;
var difference = to - element.scrollTop;
var perTick = difference / duration * 10;
setTimeout(function() {
element.scrollTop = element.scrollTop + perTick;
if (element.scrollTop === to) return;
scrollTo(element, to, duration - 10);
}, 10);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment