Skip to content

Instantly share code, notes, and snippets.

@mbostock mbostock/.block
Last active Sep 30, 2017

Embed
What would you like to do?
Smooth Scrolling
license: gpl-3.0

This example uses a custom tween that interpolates the window’s vertical scroll offset.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
padding: 40px;
}
h1, h2 {
font-family: "Helvetica Neue";
padding-bottom: 120px;
}
h2 {
padding-bottom: 240px;
}
</style>
<h1>Smooth scrolling!</h1>
<h2>Get ready to scroll, in 3, 2, 1…</h2>
<h1>Whee!</h1>
<h1>Whee!</h1>
<h1>Whee!!!</h1>
<h1>Whee!!!!!</h1>
<h1>Whee!!!</h1>
<h1>Whee!!</h1>
<h1>Whee!!!</h1>
<h1>Whee!!!!!</h1>
<h1>Whee!!!</h1>
<h1>Whee!!</h1>
<h1>Whee!!!</h1>
<h1>Whee!!!!!</h1>
<h1>Whee!!!</h1>
<h1>Whee!!</h1>
<h1>Whee!!!</h1>
<h1>Whee!!!!!</h1>
<h1>Whee!!!</h1>
<h1>Whee!!</h1>
<h1>Whee!!</h1>
<h1>Whee!!</h1>
<h1>Whee!!</h1>
<h1>Whee!!!</h1>
<h1>Whee!!!!!</h1>
<h1>Whee!!!!!!!!!!!!!</h1>
<h1>Whee!!!!!</h1>
<h1>Whee!!!</h1>
<h1>Whee!!</h1>
<h1>Whee!!!</h1>
<h1>Whee!!!!!</h1>
<h1>Whee!!!</h1>
<h1>Whee!!</h1>
<h1>Whee!!!</h1>
<h1>Whee!!!!!</h1>
<h1>Whee!!!!!!!!!!!!!!!!</h1>
<h1>Whee!!!!!</h1>
<h1>Whee!!!</h1>
<h1>Whee!!</h1>
<h1>Whee!!!</h1>
<h1>Whee!!!!!</h1>
<h1>Whee!!!</h1>
<h1>Whee!!</h1>
<h1>Whee!!!</h1>
<h1>Whee!!!!!</h1>
<h1>Whee!!!</h1>
<h1>Whee!!</h1>
<h2>All done!</h2>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
d3.transition()
.delay(1500)
.duration(7500)
.tween("scroll", scrollTween(document.body.getBoundingClientRect().height - window.innerHeight));
function scrollTween(offset) {
return function() {
var i = d3.interpolateNumber(window.pageYOffset || document.documentElement.scrollTop, offset);
return function(t) { scrollTo(0, i(t)); };
};
}
</script>
@mbostock

This comment has been minimized.

Copy link
Owner Author

mbostock commented Jan 20, 2012

Note: for Firefox you'll need to select document.documentElement rather than "body".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.