wrox Developer wrox Developer - 3 years ago 127
Javascript Question

'attr()' function not working on newly created elements

In this code,

attr()
doesn't work on newly created elements:

var rects = svgElem
.selectAll("rect")
.data(newArray);

rects.attr("fill", "black");

rects.enter().append("rect").attr("fill", "blue");

// this must work on enter and update but not working
rects.attr("height", (d, i) => {

return bar_height(d["data"]);
})


Why is that?

Here is the link to fiddle: https://jsfiddle.net/Surpreet/7mcLj6qm/

Answer Source

This is D3 v4, not D3 v3. While your code could work in D3 v3, it doesn't work anymore in D3 v4. This is the reason:

Your rects selection...

var rects = svgElem
    .selectAll("rect")
    .data(newArray);

... is an "update" selection. Therefore, all the attributes you're setting...

rects.attr("height", (d, i) => {
    return bar_height(d["data"]);
})
//etc...

... are being setting to an empty selection.

Solution: set the attributes in the "enter" selection:

rects.enter()
    .append("rect")
    .attr("fill", "blue")
    .attr("height", (d, i) => {
        return bar_height(d["data"]);
    })
    //etc...

Here is your code with that change:

var dataArray = [{
  "name": "Rushy Milkvetch",
  "latin": "Astragalus lonchocarpus Torr.",
  "light": "Green",
  "ease": 77
}, {
  "name": "Littleleaf Minerslettuce",
  "latin": "Montia parvifolia (Moc. ex DC.) Greene ssp. parvifolia",
  "light": "Mauv",
  "ease": -69
}, {
  "name": "Purple Dalea",
  "latin": "Dalea lasiathera A. Gray",
  "light": "Green",
  "ease": 12
}, {
  "name": "Strong Bladderpod",
  "latin": "Lesquerella valida Greene",
  "light": "Green",
  "ease": 33
}, {
  "name": "Marsh Cudweed",
  "latin": "Gnaphalium uliginosum L.",
  "light": "Mauv",
  "ease": 76
}, {
  "name": "Kay's Grama",
  "latin": "Bouteloua kayi Warnock",
  "light": "Mauv",
  "ease": -58
}, {
  "name": "Telegraph-plant",
  "latin": "Codariocalyx motorius (Houtt.) H. Ohashi",
  "light": "Orange",
  "ease": 73
}, {
  "name": "Western Catchfly",
  "latin": "Silene occidentalis S. Watson ssp. longistipitata C.L. Hitchc. & Maguire",
  "light": "Purple",
  "ease": 21
}, {
  "name": "Toyon",
  "latin": "Heteromeles arbutifolia (Lindl.) M. Roem. var. macrocarpa (Munz) Munz",
  "light": "Indigo",
  "ease": -21
}, {
  "name": "Woodrush Sedge",
  "latin": "Carex luzulina Olney var. atropurpurea Dorn",
  "light": "Pink",
  "ease": 19
}, {
  "name": "Conspicuous Reindeer Lichen",
  "latin": "Cladina conspicua Ahti",
  "light": "Green",
  "ease": -86
}, {
  "name": "American Mannagrass",
  "latin": "Glyceria grandis S. Watson",
  "light": "Violet",
  "ease": 78
}, {
  "name": "Greenland Pondweed",
  "latin": "Potamogeton groenlandicus Hagstr.",
  "light": "Puce",
  "ease": 36
}, {
  "name": "Santa Barbara Island Liveforever",
  "latin": "Dudleya traskiae (Rose) Moran",
  "light": "Purple",
  "ease": 94
}, {
  "name": "Harrisella",
  "latin": "Harrisella Fawc. & Rendle",
  "light": "Puce",
  "ease": -20
}];
var height = window.innerHeight,
  width = window.innerWidth;
var svgElem = d3.select("#content").append("svg")
  .attr("width", width)
  .attr("height", height)

var color = d3.scaleLinear()
  .domain([-100, 0, +100])
  .range(["red", "white", "green"]);



update(dataArray);

function update(dataArray) {
  var newArray = dataArray.map(function(item) {
    item["data"] = Math.floor(Math.random() * 100);
    return item;
  });
  var barWidth = width / dataArray.length;

  var elemDomain = d3.extent(newArray, function(d) {
    return d.data
  });

  var bar_height = d3.scaleLinear()
    .domain(elemDomain)
    .range([0, height]);

  var rects = svgElem
    .selectAll("rect")
    .data(newArray);

  // rects.attr("fill","black");

  rects.enter().append("rect").attr("fill", "blue")
    .attr("height", (d, i) => {
      return bar_height(d["data"]);
    }).attr("width", function(w) {
      return barWidth;
    }).attr("x", function(x, i) {
      return i * barWidth;
    }).attr("y", function(data, i) {
      return height - bar_height(data["data"]);
    });

}
<script src="https://d3js.org/d3.v4.min.js"></script>
<div id="content"></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download