I'm using d3 to display data I'm receiving via websockets as a simple html table. This works fine so far. Now I need to visualize changes to that data, so I would like to use transitions with background-color or something to visually highlight the changed cells.
Here's the code I'm using:
var data = new d3.map({"In1": false, "Reg1": 0815});
data.set("In2", true);
data.set("Reg2", 4711);
var table = d3.select("#foo").append("table").attr("class", "table table-bordered table-striped");
var thead = table.append("thead");
thead.append("th").text("Test");
var tbody = table.append("tbody");
update(data.entries());
When I receive new data via websockets, I simply update the data map via data.set(key,value) and call the update function:
function update(data) {
var rows = tbody.selectAll("tr")
.data(data);
rows.exit().remove();
rows.enter().append("tr");
// create a cell in each row for each column
var cells = rows.selectAll("td")
.data(function (row) {
return [row.key, row.value];
});
cells.enter().append("td");
cells.text(function (d) { return d; });
cells.transition().style('color', 'red').transition().style('color', 'green');
}
The problem is that the update selection seems to apply to ALL elements, not only to those whose values actually changed (that is what I hoped it would be). Is this something I'm just doing wrong, or is this generally the case? If so, how could I apply the transitions only to the actually changed elements?
edit: Created a jsfiddle, you'll see that all table cells are animated, I only want the value-cell of "Reg2" to be....
D3 doesn't offer anything out of the box for this, but one approach is to store the old data with the element and then, on update, compare the new to the old to see if it has changed. This way, you can filter your elements and apply the transition only to the ones where the data has changed:
cells.filter(function() { return this.__olddata__ != this.__data__; })
.each(function() { this.__olddata__ = this.__data__; })
.transition().style('color', 'red').transition().style('color', 'green');
Complete demo here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With