Example 7

HTML

<div id="target"></div>
<p>
    <button id="add">Add Rivendell</button>
    <button id="remove">Remove Ravenclaw</button>
</p>

CSS

button, input {
    padding: 5px 8px;
}

JavaScript

var houses = [{
    name: "Gryffindor",
    color: "orange",
    score: 420
}, {
    name: "Ravenclaw",
    color: "lightblue",
    score: 200
}, {
    name: "Hufflepuff",
    color: "yellow",
    score: 350
}, {
    name: "Slytherin",
    color: "green",
    score: 700
}, ];

var rows = d3.select("#target");

var updateRows = function () {
    var join = rows.selectAll("p").data(houses);
    join.enter().append("p")
        .style({
        "background-color": function (house) {
            return house.color;
        },
            "width": function (house) {
            return house.score + "px";
        }
    })
        .text(function (house) {
        return house.name
    });

    join.style({
        "width": function (house) {
            return house.score + "px";
        }
    });

    join.exit().remove();
};

updateRows();

d3.select("#add").on('click', function () {
    var rivendell = {
        name: "Rivendell",
        score: 20,
        color: "#fcc"
    };
    houses.push(rivendell);
    console.log(houses);
    updateRows();
});

d3.select("#remove").on('click', function () {
    var targetIndex = -1;
    for (var i = 0; i < houses.length; i++) {
        if (houses[i].name === "Ravenclaw") {
            targetIndex = i;
            break;
        }
    }
    if (targetIndex !== -1) houses.splice(targetIndex, 1);
    updateRows();
});