Created
August 8, 2016 14:00
-
-
Save 599316527/e77247fb11fbfc35adeb7310078ea7b2 to your computer and use it in GitHub Desktop.
Scroll to target element smoothly
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
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