charliemagee
charliemagee

Reputation: 693

d3 scoping causes SVG to revert to initial data?

I'm new to d3.js and still a beginner in javascript in general. I've got d3 correctly drawing a single SVG rectangle based on a single value in an array. When I increase the value of the number in the area via an input field and then call the reDraw function, the rectangle changes to the new size for just a second and then switches back to the initial size. I'm thinking I must have a scoping problem, but can't figure it out. Any ideas?

var dataset, h, reDraw, svg, w;

w = 300;

h = 400;

dataset = [1000];

// Create SVG element
svg = d3.select("#left").append("svg").attr("width", w).attr("height", h);

// set size and position of bar
svg.selectAll("rect").data(dataset).enter().append("rect").attr("x", 120).attr("y", function(d) {
  return h - (d / 26) - 2;
}).attr("width", 60).attr("height", function(d) {
  return d / 26;
}).attr("fill", "rgb(3, 100, 0)");

// set size and position of text on bar
svg.selectAll("text").data(dataset).enter().append("text").text(function(d) {
  return "$" + d;
}).attr("text-anchor", "middle").attr("x", 150).attr("y", function(d) {
  return h - (d / 26) + 14;
}).attr("font-family", "sans-serif").attr("font-size", "12px").attr("fill", "white");

// grab the value from the input, add to existing value of dataset
$("#submitbtn").click(function() {
  localStorage.setItem("donationTotal", Number(localStorage.getItem("donationTotal")) + Number($("#donation").val()));
  dataset.shift();
  dataset.push(localStorage.getItem("donationTotal"));
  return reDraw();
});

// redraw the rectangle to new size
reDraw = function() {
  return svg.selectAll("rect").data(dataset).attr("y", function(d) {
    return h - (d / 26) - 2;
  }).attr("height", function(d) {
    return d / 26;
  });
};

Upvotes: 0

Views: 197

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109262

You need to tell d3 how to match new data to existing data in the reDraw function. That is, you're selecting all rectangles in reDraw and then binding data to it without telling it the relation between the old and the new. So after the call to data(), the current selection (the one you're operating on) should be empty (not sure why something happens for you at all) while the enter() selection contains the new data and the exit() selection the old one.

You have several options to make this work. You could either operate on the enter() and exit() selections in your current setup, i.e. remove the old and add the new, or restructure your data such that you're able to match old and new. You could for example use an object with appropriate attributes instead of a single number. The latter has the advantage that you could add a transition from the old to the new size.

Have a look at this tutorial for some more information on data joins.

Edit:

Turns out that this was actually not the issue, see comments.

Upvotes: 1

Related Questions