Last active
December 15, 2018 12:20
-
-
Save juusaw/c52f4addcdb4b2875d14fc9525197cd5 to your computer and use it in GitHub Desktop.
Animated scroll to target in pure JS
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
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