Animated List (D3 w/svg)

Ehh.... not great.

by Ryan

HTML

<script src="https://d3js.org/d3.v3.min.js"></script>

CSS

.container {
    position: relative;
}
.list-item {
    stroke: black;
    stroke-width: 1px;
    fill: white;
}
.enter {
    stroke: green;
}
.exit {
    stroke: red;
}

JavaScript

var boxHeight = 30;
var rawData = [ 
    { name: "a", score: 0 }, 
    { name: "b", score: 1 }, 
    { name: "c", score: 2 }, 
    { name: "d", score: 3 }, 
    { name: "e", score: 4 }, 
    { name: "f", score: 5 }, 
    { name: "g", score: 6 }, 
    { name: "h", score: 7 }, 
    { name: "i", score: 8 }, 
    { name: "j", score: 9 }
];

d3.select("body").append("div")
    .text("Update")
    .on("click", function(d,i) { update(); });

var container = d3.select("body").append("div")
    .attr("class", "container")
    .append("svg").append("g");

var redraw = function(data){
    var toDraw = data.sort();

    // Update the container size
    container.attr("height", boxHeight * data.length);
    
    // Join
    var div = container.selectAll(".list-item")
        .data(data, function(d) { return d.name; } );
    
    // Update
    div.attr("class", "list-item")
        .attr("y", function(d, i) { return boxHeight * i; } );
    
    // Enter
    div.enter().append("rect")
        .attr("class", "list-item enter")
        .attr("x", 0)
        .attr("y", function(d, i) { return boxHeight * i; } )
        .attr("height", boxHeight - 4)
        .attr("width", 100);
    
    //Exit
    div.exit()
        .attr("class", "list-item exit")
        .transition().duration(500)
            .remove();

};

var update = function(){
    var newData = [];
    rawData.forEach(function(d){
        if(0 !== Math.floor(Math.random() * 5)){
            newData.push(d);
        }
    });
    redraw(newData);
};

redraw(rawData);

d3.select("body").append("div")
    .text("Below");