Created
June 1, 2017 13:32
-
-
Save dzava/3128eb2c1a87845b092c058be81445a6 to your computer and use it in GitHub Desktop.
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
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