D3 Transitions & Update - Vincentvanleeuwen/frontend-data GitHub Wiki
I wanted to add a transition to the lollipops so that they don't randomly reappear in another spot. I knew of the function .transition() so I tried adding that to the lollipops the same way as I did with the lollistick.
// Update lollipop
target.selectAll('.lollipop')
.data(getPlaces(data, currentType))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.join('circle').transition().duration(500)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.attr('cx', d => x(d[currentColumn]))
.attr('cy', d => y(d.location) + 4.5)
.on("mouseover", (event, d) => {
select('.tooltip').transition()
.duration(200)
.style("opacity", .9);
select('.tooltip').html(`${d[currentColumn]} ${currentColumn === 'capacity' ? 'parking spots' :
'charging points'} `)
.style('left', `${event.pageX}px`)
.style('top', `${event.pageY - 28}px`);
});
By placing it right after the join('circle') you'd imagine it puts a transition on all the circles that are being created. However this is a unique case. Because we are calling .transition on the join('circle') it automatically makes a transition object from all those circles. Because of this you are supposed to make a variable of all the circles.
// Update lollipop
const lollipop = target.selectAll('.lollipop').data(getPlaces(data, currentType)).join('circle');
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
lollipop
.transition().duration(500)
.attr('cx', d => x(d[currentColumn]))
.attr('cy', d => y(d.location) + 4.5)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
lollipop
.on("mouseover", (event, d) => {
select('.tooltip').transition()
.duration(200)
.style("opacity", .9);
select('.tooltip').html(`${d[currentColumn]} ${currentColumn === 'capacity' ? 'parking spots' :
'charging points'} `)
.style('left', `${event.pageX}px`)
.style('top', `${event.pageY - 28}px`);
});
By creating a separate variable of the circles, you can apply event listeners and transitions in different calls, because you're not changing the type of element of the circles. You also need to specify what data is changing after you've put down the .transition(). If you specify the changed data before calling the transition, it'll not know where to transition to.