Reputation: 109
I was working on adding in transitions to my bar chart where they start from the axis and rise up into the desired height. I got the transitions to work but then the mouseover event no longer worked. I am confused as to why d
is undefined if I have already appended the data to the plwdhBar
object and am calling it later in the code.
After looking at similar solutions, it seemed that the solution was to call the bar chart bars once to set them up from the data, then to add the transition, then to add in the mouseover event.
Here is what I currently have: (working transition but not working mouseover, results in error for showTooltip(d)
function)
var plwdhBar = svg.append("g")
d3.csv("Data/"+name+".csv").then(function(dataset) {
plwdhBar.selectAll("plwdhBar") //bar2
.data(dataset)
.enter()
.append("rect")
.attr("class","plwdhBar")
.attr("width", 30)
.attr("fill", bar2Color)
.attr("x",(d)=>xScale(d.year)+(barW/2)-15)
.attr("y", h-margin.bottom)
.transition()
.duration(200)
.attr("y",(d)=>yBarScale(d.plwdh))
.attr("height", (d)=>(h-yBarScale(d.plwdh)) -margin.bottom)
plwdhBar.on("mouseover",function(d){
showTooltip(d);
}).on("mouseout",function(){
removeTooltip();
});
}
I have also tried taking out the lines of code for the transition and making it:
plwdhBar.transition()
.duration(200)
.attr("y",(d)=>yBarScale(d.plwdh))
.attr("height", (d)=>(h-yBarScale(d.plwdh)) -margin.bottom)
however then that also resulted in an undefined error for d
The error in all the situations is TypeError: d is undefined
and occurs in the first code snippet when then removeToolTip(d)
function is called and in the scenario where the second code snippet is implemented the error occurs on the .attr("y",(d)=>yBarScale(d.plwdh))
line.
Upvotes: 1
Views: 91
Reputation: 102194
This is your plwdhBar
variable:
var plwdhBar = svg.append("g");
It's just this, nothing more. No data bound to it. Keep this in mind because this information is important for understanding what's wrong here.
Then you do:
plwdhBar.selectAll("plwdhBar")
.data(dataset)
.enter()
.append("rect")
//etc...
This, of course, is appending your rectangles, and if you added the listeners in that chain it would work. But pay attention to the fact that this does not change what plwdhBar
is, it keeps being just var plwdhBar = svg.append("g");
, as we showed initially.
Therefore, when you later do...
plwdhBar.on("mouseover",function(d){
showTooltip(d);
})
... you get the error because, of course, there is no data here.
Solution: name your selections!
For instance:
var foo = plwdhBar.selectAll("plwdhBar")
.data(dataset)
.enter()
.append("rect")
//etc...
Now you can do:
foo.on("mouseover",function(d){
showTooltip(d);
})
However, there is an important advice: transitions also have a method named on
. So, remove the transition from the main chain, otherwise you'll get another error (not related to this one). You can add the transition separately:
foo.transition()
//etc...
Upvotes: 1