scroll to anchors
by Oleh Kotsubko
JavaScript
export const scrollToAnchors = (item) => {
const easeInCubic = function (t) { return t<.5 ? 8*t*t*t*t : 1-8*(--t)*t*t*t }
const scrollToElem = (startTime, currentTime, duration, scrollEndElemTop, startScrollOffset) => {
const runtime = currentTime - startTime;
let progress = runtime / duration;
progress = Math.min(progress, 1);
const ease = easeInCubic(progress);
window.scroll(0, startScrollOffset + (scrollEndElemTop * ease));
if(runtime < duration){
requestAnimationFrame((timestamp) => {
const currentTime = timestamp || new Date().getTime();
scrollToElem(startTime, currentTime, duration, scrollEndElemTop, startScrollOffset);
})
}
}
for(let i = 0; i < item.length; i++){
const elem = item[i];
elem.addEventListener('click',function(e) {
e.preventDefault();
// 1. Get the element id to which you want to scroll
const scrollElemId = e.target.href.split('#')[1];
// 2. find that node from the document
const scrollEndElem = document.getElementById(scrollElemId);
// 3. and well animate to that node..
const anim = requestAnimationFrame((timestamp) => {
const stamp = timestamp || new Date().getTime();
const duration = 1200;
const start = stamp;
const startScrollOffset = window.pageYOffset;
const scrollEndElemTop = scrollEndElem.getBoundingClientRect().top;
scrollToElem(start, stamp, duration, scrollEndElemTop, startScrollOffset);
})
})
}
}