Last active
November 11, 2016 09:46
-
-
Save SysVoid/d659b67c2de1e789fa67891c61b88435 to your computer and use it in GitHub Desktop.
JavaScript smooth scrolling with interpolation.
This file contains hidden or 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
<!doctype html> | |
<html> | |
<head> | |
<title>Example</title> | |
<style>.amazingDiv {position: relative;top: 2000px;padding-bottom: 1000px;}</style> | |
</head> | |
<body> | |
<div class="amazingDiv"> | |
Interpolation, bro. | |
</div> | |
<script type="text/javascript" src="https://gist.githubusercontent.com/SysVoid/d659b67c2de1e789fa67891c61b88435/raw/smoothScroll.js"></script> | |
</body> | |
</html> |
This file contains hidden or 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
const smoothScroll = (element, time, callback) => { | |
if (time == null) { | |
time = 500; | |
} | |
let delta = 1000 / 30; | |
let timeElapsed = 0; | |
let from = window.scrollY; | |
let to = element.getBoundingClientRect().top; | |
let interval = setInterval(() => { | |
let progress = timeElapsed / time; | |
let y = (progress * to) + ((1 - progress) * from); | |
window.scrollTo(0, y); | |
timeElapsed += delta; | |
if (timeElapsed >= time) { | |
window.scrollTo(0, to); | |
window.clearInterval(interval); | |
if (typeof callback === 'function') { | |
callback(); | |
} | |
} | |
}, delta); | |
} |
This file contains hidden or 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 smoothScroll(element, time, callback) { | |
if (time == null) { | |
time = 500; | |
} | |
var delta = 1000 / 30; | |
var timeElapsed = 0; | |
var from = window.scrollY; | |
var to = element.getBoundingClientRect().top; | |
var interval = setInterval(function () { | |
var progress = timeElapsed / time; | |
var y = (progress * to) + ((1 - progress) * from); | |
window.scrollTo(0, y); | |
timeElapsed += delta; | |
if (timeElapsed >= time) { | |
window.scrollTo(0, to); | |
window.clearInterval(interval); | |
if (typeof callback === 'function') { | |
callback(); | |
} | |
} | |
}, delta); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment