Reputation: 369
I have a bar chart. I'd like to do the same option, but instead of highlighting, it should draw the line. Is it possible to do?
Upvotes: 2
Views: 79
Reputation: 22922
The easiest option I can think of is to just append
a <line>
to the SVG whenever you mouseover
a bar, and remove that line when you mouseout
. It's similar to the solution proposed by @ckersch, except that it has more overhead (you're changing the DOM every mouseover
/mouseout
), but is easier to implement and doesn't change the structure of your SVG at all. You can add the following when you append the bars:
.on("mouseover", function(d){
svg.append("line")
.attr("class", "mouseover-line")
.attr("x1", x(d[0]) + x.rangeBand()/2)
.attr("x2", x(d[0]) + x.rangeBand()/2)
.attr("y1", y(0))
.attr("y2", y(d[1]));
.style("stroke", "#000")
})
.on("mouseout", function(){
d3.selectAll(".mouseover-line").remove();
});
Working fiddle here.
Upvotes: 2
Reputation: 7687
It's possible with a combination of css and javascript. You can define css for a class as follows:
.hiddenLine{ opacity: 0; }
If you build your dom with both bars and lines as children of g
elements, with bars first so the lines render on top of them, like so:
...
<g class="bar">
<rect></rect>
<line></line>
</g>
//more bars
...
The following javascript will create the hover affect:
d3.select('.bars')
.on('mouseover', function(d){
d3.select(this).select('line').classed('hiddenLine', false);
})
.on('mouseout', function(d){
d3.select(this).select('line').classed('hiddenLine', true);
});
Upvotes: 2