Last active
November 21, 2015 00:50
-
-
Save MikeDigitize/4c7dc5576cfb32243cf9 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 scrollToElement(scrollAmount = 20) { | |
let findPos = (el, elPos = 0) => { | |
if (el.offsetParent) { | |
do { | |
elPos += el.offsetTop; | |
} while (el = el.offsetParent); | |
} | |
return elPos; | |
}; | |
let scrollUp = (yPos, yStop) => { | |
let scroll = () => { | |
yPos -=scrollAmount; | |
window.scrollTo(0, yPos); | |
}; | |
let timer = setInterval(() => { | |
if(scrollAmount > 0 && yPos <= yStop || scrollAmount < 0 && yPos >= yStop) { | |
clearInterval(timer); | |
} | |
else { | |
scroll(); | |
} | |
}, 5); | |
}; | |
return selector => { | |
let elementPos = findPos(document.querySelector(selector)); | |
let scrollPos = window.pageYOffset; | |
scrollAmount = elementPos > scrollPos ? -Math.abs(scrollAmount) : +Math.abs(scrollAmount); | |
scrollUp(scrollPos, elementPos); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment