Skip to content

Instantly share code, notes, and snippets.

@SysVoid
Last active November 11, 2016 09:46
Show Gist options
  • Save SysVoid/d659b67c2de1e789fa67891c61b88435 to your computer and use it in GitHub Desktop.
Save SysVoid/d659b67c2de1e789fa67891c61b88435 to your computer and use it in GitHub Desktop.
JavaScript smooth scrolling with interpolation.
<!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>
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);
}
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