Skip to content

Instantly share code, notes, and snippets.

@Anks
Last active December 25, 2015 09:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Anks/6958322 to your computer and use it in GitHub Desktop.
Save Anks/6958322 to your computer and use it in GitHub Desktop.
Transitioning numbers using d3.js
<!DOCTYPE html>
<meta charset="utf-8">
<style></style>
<body>
<h2>Transitioning numbers</h2>
<h3 data-value="0" id="the-number">0</h3>
<input type="number" value="0" id="new-number" step="100" />
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://documentcloud.github.io/underscore/underscore-min.js"></script>
<script>
var formatNumber = d3.format(",d");
var createNumericTween = function (oldValue, newValue) {
return function() {
var i = d3.interpolateRound(oldValue, newValue);
return function(t) {
this.textContent = formatNumber(i(t));
};
};
};
var transitionNumber = function (sel, newValue, options) {
var params = _.extend({ initialValue: 0, duration: 500, tween: createNumericTween, format: formatNumber }, options);
var old = parseInt(sel.attr('data-value')) || params.initialValue;
sel.attr('data-value', newValue)
.transition()
.duration(params.duration)
.tween('text', params.tween(old, newValue, params.format));
};
var newNumber = document.getElementById('new-number'),
selection = d3.select('#the-number');
newNumber.addEventListener('change', function () {
transitionNumber(selection, newNumber.value);
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment