Fixing the Exit Transition
The exit transition can be animated by overriding the default behavior of the join() method.
We'll cover the following...
We are going to animate the bars when they are leaving the document. We’ve already discussed why this is happening. In summary, the bars are removed before the transition is applied. Therefore, D3 will not animate the elements.
Transitioning the exit selection
We can fix this issue by overriding the default behavior in the join()
function. In our script, we are passing in a function to the join()
function. This function will run during the enter selection. This time around, we are interested in running a function during the exit selection. We will need to pass in another two arrow functions.
// Draw Barsctr.selectAll('rect').data(newDataset).join((enter) => enter.append('rect').attr('width', d => d3.max([0, xScale(d.x1) - xScale(d.x0) - padding])).attr("height", 0).attr('x', d => xScale(d.x0)).attr("y", dimensions.ctrHeight).attr('fill', '#01c5c4'),(update) => update,(exit) => exit.transition().attr('y', dimensions.ctrHeight).attr('height', 0).remove()).transition().duration(3000).attr('width', d => d3.max([0, xScale(d.x1) - xScale(d.x0) - padding])).attr("height", d => dimensions.ctrHeight - yScale(yAccessor(d))).attr('x', d => xScale(d.x0)).attr("y", d => yScale(yAccessor(d))).attr('fill', '#01c5c4')
The second function will run for the update selection. The update selection is a list of elements that need to be updated. In this example, we are accepting the update selection as an argument and returning it. This is the default behavior. We will not override the default behavior because the animation works fine without needing to do anything.
The third function will run for the exit selection. This selection contains a list of elements that need to be removed. Like before, we ...