Reputation: 187
I'm currently having a little trouble wrapping my head round why the width attribute of 'rect' does not update, despite the variable being passed to it updating. As you can see I am trying to replace the first property in the array 'data' to the value being input, which should ensue the change of width of the rect in the draw() function. (n) updates accordingly when it is logged in the 'draw' function, but doesn't alter the width of the bar...
Here is my code:
HTML:
<p>
<label for="nValue" style="display: inline-block; width: 240px; text-align: right"></label>
<input id="nValue" max="100" min="0" step="10" type="number" value="0"></input>
</p>
<svg class = "chart"></svg>
CSS:
svg {
background-color: red;
position: absolute;
top: 10%;
left: 10%;
}
JS:
var data = [];
d3.select("#nValue").on("input", function() {
number(+this.value);
});
number(0);
function number(nValue) {
data[0] = nValue;
draw(nValue);
}
// graph is drawn here
function draw(n) {
var width = 300;
var barHeight = 10;
var chart = d3.select(".chart")
.attr("width", width)
.attr("height", barHeight * data.length);
var bar = chart.selectAll("g")
.data(data)
.enter().append("g")
.attr("transform", function(d, i) {
return "translate(0," + i * barHeight + ")";
});
bar.append("rect")
.attr("width", n)
.attr("height", barHeight - 1);
console.log('n =' + n);
console.log('0 =' + data[0]);
}
Thanks
Upvotes: 0
Views: 1092
Reputation: 14053
It's because you're setting bar
to the enter()
selection, which consists strictly of newly added data values. Yet you're not adding a new data value when the input changes, you're simply changing an existing value (data[0]
). After the first time draw()
is executed, bar
will be an empty selection, so appending rectangles and setting their dimensions will have no effect.
Upvotes: 1