Skip to content

Instantly share code, notes, and snippets.

@humbletim
Last active December 16, 2015 22:29
Show Gist options
  • Save humbletim/5507619 to your computer and use it in GitHub Desktop.
Save humbletim/5507619 to your computer and use it in GitHub Desktop.
transition scrollTop on a DIV
<!doctype html>
<html>
<head>
<script src="http://mbostock.github.com/d3/d3.js"></script>
<style>
body { font-family: sans-serif; font-size: .8em; background-color: #ccc; }
#scrollable { height: 100px; overflow: hidden; border: solid 1px white;}
#scrollable .inner { height: 1000px; }
#scrollable .content {
height: 94px; margin: 2px 0;
background-color: steelblue;
color: white;
}
</style>
</head>
<body>
<div id="scrollable">
<div>
<button id="down">scroll down</button>
<script> for(var i=0; i < 10; i++) document.write("<div class='content'>"+i+"</div>"); </script>
<button id="up">scroll up</button> <span>inspired by mbostock's <a href="https://gist.github.com/mbostock/1649463">Smooth Scrolling gist</a></span>
</div>
</div>
<script>
var scrollable = d3.select("#scrollable");
d3.select("#down").on('click', function() {
var scrollheight = scrollable.property("scrollHeight");
d3.select("#scrollable").transition().duration(3000)
.tween("uniquetweenname", scrollTopTween(scrollheight));
});
d3.select("#up").on('click', function() {
d3.select("#scrollable").transition().duration(1000)
.tween("uniquetweenname", scrollTopTween(0));
});
function scrollTopTween(scrollTop) {
return function() {
var i = d3.interpolateNumber(this.scrollTop, scrollTop);
return function(t) { this.scrollTop = i(t); };
};
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment