Skip to content

Instantly share code, notes, and snippets.

@tmcw
Created March 17, 2015 01:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmcw/41137d930284600d3134 to your computer and use it in GitHub Desktop.
Save tmcw/41137d930284600d3134 to your computer and use it in GitHub Desktop.
d3 now (d3 without transitions)

Remove transitions from d3 can make everything much simpler.

/* global d3 */
d3.selection.prototype.now = function(tagName, data, maker) {
var key = function(v) { return v; };
if (maker === undefined) {
maker = data; data = [1];
}
var selection = this.selectAll(tagName)
.data(data, key);
selection.enter().append(tagName);
selection.exit().remove();
selection.each(function(d) {
maker(d3.select(this), d);
});
return this;
};
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<style>
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
position: relative;
width: 960px;
}
</style>
</head>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="d3now.js"></script>
<script>
var randomColors = [], numberOfColors = 20;
for (var i = 0; i < 20; i++) {
randomColors.push(['rgb(' +
~~(Math.random() * 255),
~~(Math.random() * 255),
~~(Math.random() * 255)].join(',') + ')');
}
function draw() {
d3.select(document.body)
.now('input', function(element) {
element
.attr('type', 'range')
.attr('min', 0)
.attr('max', 20)
.on('input', function() {
numberOfColors = parseInt(this.value);
draw();
});
})
.now('div', randomColors.slice(0, numberOfColors), function(element, color) {
return element
.style('background', color)
.now('div', function(element) {
element.text(color);
});
});
}
draw();
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment