Skip to content

Instantly share code, notes, and snippets.

@599316527
Created August 8, 2016 14:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 599316527/e77247fb11fbfc35adeb7310078ea7b2 to your computer and use it in GitHub Desktop.
Save 599316527/e77247fb11fbfc35adeb7310078ea7b2 to your computer and use it in GitHub Desktop.
Scroll to target element smoothly
function smoothScrollTo(selector, duration) {
const FPS = 24
let currentScrollY = window.scrollY
let targetScrollY = document.querySelector(selector).getBoundingClientRect().top + currentScrollY
let deltaY = (targetScrollY - currentScrollY) / (duration * FPS)
let interval = 1E3 / FPS
let scrollTimer
let scrollCallback = []
function scroll() {
currentScrollY += deltaY
window.scrollTo(0, currentScrollY)
scrollTimer = setTimeout(function () {
if (deltaY < 0 ? currentScrollY > targetScrollY : currentScrollY < targetScrollY) {
scroll()
} else {
doThen()
}
}, interval)
}
function cancel() {
clearTimeout(scrollTimer)
}
function then(func) {
if (scrollCallback.indexOf(func) < 0) {
scrollCallback.push(func)
}
}
function doThen() {
scrollCallback.forEach(function (func) {
func()
})
}
scroll()
return { cancel, then }
}
smoothScrollTo('.contentinfo', 2).then(function () {
console.log('done');
let handler = smoothScrollTo('#wiki-content', 4)
setTimeout(function () {
handler.cancel()
}, 999)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment