Skip to content

Instantly share code, notes, and snippets.

@juusaw
Last active December 15, 2018 12:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save juusaw/c52f4addcdb4b2875d14fc9525197cd5 to your computer and use it in GitHub Desktop.
Save juusaw/c52f4addcdb4b2875d14fc9525197cd5 to your computer and use it in GitHub Desktop.
Animated scroll to target in pure JS
var links = document.getElementsByClassName('scroll-link');
for (var i = 0; i < links.length; i++) {
links[i].onclick = scroll;
}
function scroll(e) {
e.preventDefault();
var id = this.getAttribute('href').replace('#', '');
var target = document.getElementById(id).getBoundingClientRect().top;
animateScroll(target);
}
function animateScroll(targetHeight) {
targetHeight = document.body.scrollHeight - window.innerHeight > targetHeight + scrollY ?
targetHeight : document.body.scrollHeight - window.innerHeight;
var initialPosition = window.scrollY;
var SCROLL_DURATION = 30;
var step_x = Math.PI / SCROLL_DURATION;
var step_count = 0;
requestAnimationFrame(step);
function step() {
if (step_count < SCROLL_DURATION) {
requestAnimationFrame(step);
step_count++;
window.scrollTo(0, initialPosition + targetHeight * 0.25 * Math.pow((1 - Math.cos(step_x * step_count)), 2));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment