I've prepared a small fiddle to illustrate the problem here
I'm having an issue using d3's exit function to remove elements from the dom.
Say I have an array of 10 elements:
var data = [1 ,4, 5, 6, 24, 8, 12, 1, 1, 20]
I use this data to create a simple horizontal bar chart using d3
d3.selectAll('rect')
.data(data)
.enter()
.attr("class", "rectangle")
.attr("stroke", "black")
.attr("stroke-width","1px")
.attr("fill","none")
.attr("x", 0)
.attr("y", function(d, i) { return 25 * i; } )
.attr("width", function(d) { return 22 * d; } )
.attr("height", "20");
Now after a short delay I'd like to prune my dataset so all that I have left is
var truncatedData = [4,5]
d3.selectAll('rect')
.data(truncatedData )
.exit()
.transition()
.delay(3000)
.remove();
Data is removed successfully but it still shows the first two elements 1,4 instead of 4,5.
How can I remove all but [4,5] from the dom?
exit() function in D3. js is used to remove the elements or tags which correspond to the old data or in simple words This is used to update the DIV elements that were created before with the new data given.
selectAll() function in D3. js is used to select all the element that matches the specified selector string. Parameters: This function accepts single parameter HTML tag as a parameter. Return Value: This function returns the selected elements.
By default, d3 matches elements given to .data()
by their index and not value. That is, giving it a two-element array in the second call means that the first two elements from the first call (indices 0 and 1) are retained.
To fix this issue in your case, give a function to match elements to the second call to .data()
, i.e.
.data([5, 6], function(d) { return(d); })
Fixed jsfiddle here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With