You are assigning the event handlers before you append
the rect
s.
The first time you go from Year to Quarter the tooltip only appears on the first column because the event has only been applied to the first rect
s making up the column because there was only one column in the Year view.
Likewise, going from Quarter to Month, the tooltip only appears on the first four columns because that's how many columns were in the Quarter view.
When you click Quarter and Month for the 2nd (or more) occasion the rect
s now exist from the first time the button was clicked and the event handlers can attach.
The consistent behaviour you're looking for is just a matter of taking this code
var rect = layer.selectAll("rect")
.data(function (d) {
return d;
}) // ------------------------------------------------------------ remove from below ↓↓↓↓↓
.on("mouseover", function() { tooltip.style("display", null); })
.on("mouseout", function() { tooltip.style("display", "none"); })
.on("mousemove", function(d) {
var xPosition = d3.mouse(this)[0] - 15;
var yPosition = d3.mouse(this)[1] - 25;
tooltip.attr("transform", "translate(" + xPosition + "," + yPosition + ")");
tooltip.select("text").text(d.y);
});
And moving it down to the section where you append
rect
s just after the // Draw Legends ends
comment:
rect.enter().append("rect")
.attr("x", function (d) {
return x(d.x);
})
.attr("y", function (d) {
return y(d.y + d.y0);
})
.attr("height", function (d) {
return y(d.y0) - y(d.y + d.y0);
})
.attr("width", x.rangeBand()) // -------------------------------- add below here ↓↓↓↓↓
.on("mouseover", function() { tooltip.style("display", null); })
.on("mouseout", function() { tooltip.style("display", "none"); })
.on("mousemove", function(d) {
var xPosition = d3.mouse(this)[0] - 15;
var yPosition = d3.mouse(this)[1] - 25;
tooltip.attr("transform", "translate(" + xPosition + "," + yPosition + ")");
tooltip.select("text").text(d.y);
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…