Example 6

HTML

<div id="target"></div>
<p>
    <button id="gryf" name="gryf">Ten points to Gryffindor!</button>
    <button id="slyth" name="slyth">Ten points from Slytherin!</button>
</p>
<p>
    <input type="text" pattern="[0-9]*" id="hufflepoints" />
    <button id="huffl" name="huffl" disabled>Grant points to Hufflepuff!</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 }, 
];


d3.select("#target").selectAll("p")
    .data(houses)
    .enter()
    .append("p")
    .text(function(house) {
        return house.name;
    })
  .style("background-color",function(house) {
    return house.color;
  })
  .style("width",function(house) {
    return house.score + "px";
  });
  
// Click handler
d3.select("#gryf").on('click',function() {
  d3.event.preventDefault();
  houses[0].score += 10;
  d3.select("#target").selectAll("p")
    .data(houses)
    .transition()
    .style("width",function(house) {
       return house.score + "px";
    });
});

d3.select("#slyth").on('click',function() {
  d3.event.preventDefault();
  houses[3].score -= 10;
  d3.select("#target").selectAll("p")
    .data(houses)
    .transition()
    .style("width",function(house) {
      return house.score + "px" 
    });
});

// Let's get a little fancy here, enabling
// and disabling the submit button depending
// on content.
d3.select("#hufflepoints").on('keyup',function() {
  if(score = parseInt(this.value,10)) {
    d3.select("#huffl").attr("disabled",null);
  } else {
    d3.select("#huffl").attr("disabled","disabled");
  }
});

d3.select("#huffl").on('click',function() {
  d3.event.preventDefault();
  // Brute-forcing this:
  points = d3.select("#hufflepoints")[0][0].value
  points = Math.abs(points);
  if (points > 100) points = 100;
  houses[2].score += points;  
  d3.select("#target").selectAll("p")
    .data(houses)
    .transition()
    .style("width",function(house) {
      return house.score + "px" 
    });  
});