Last active
December 25, 2015 09:59
-
-
Save Anks/6958322 to your computer and use it in GitHub Desktop.
Transitioning numbers using d3.js
This file contains 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> | |
<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