Skip to content

Instantly share code, notes, and snippets.

@Johannestegner
Created February 20, 2018 10:40
Show Gist options
  • Save Johannestegner/18fc4b398010e2c651767fdb4ac2149f to your computer and use it in GitHub Desktop.
Save Johannestegner/18fc4b398010e2c651767fdb4ac2149f to your computer and use it in GitHub Desktop.
Naive scroll in to view implementation
export default function(targetSelector, speed) {
let current = (
(document.documentElement.scrollTop || document.body.scrollTop)
-
(window.innerHeight / 2)
);
let target = document.querySelector(targetSelector).getBoundingClientRect();
let offset = (target.bottom - (target.height / 2)) + current;
let lastFrame = Date.now();
let move = function() {
let delta = (Date.now()-lastFrame) / 1000;
lastFrame = Date.now();
if (window.scrollY - offset >= 1) {
return;
}
window.scrollBy(0, (offset * (delta * speed)));
requestAnimationFrame(move);
};
move();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment