user3206082 user3206082 - 3 months ago 36
Javascript Question

d3 - hover on legend to highlight the respective data

Successfully created a heatmap using d3.

Here's the FIDDLE.

I have some basic idea on using d3's

mouseover
events. But now I wanted move a step ahead.

This is what I'm looking for. When I hover on a legend, I wanted the hovered legend's respective data to be highlighted in the chart.

Can someone help me to achieve it?

Answer

You're not binding the data to the legend, which makes this task a bit more difficult, but you can still do it fairly easily. The idea is to assign a class defined by the fill color to the rect elements and then select accordingly in the mouseover handler. The code looks like this.

// for the rectangles
.attr("class", function(d) {  
  return "hour bordered " + "color-" + colorScale(d.value).substring(1);
})

// for the legend
.on("mouseover", function(d, i) {
  svg.selectAll("rect.color-" + colors[i].substring(1)).style("stroke", "blue");
})
.on("mouseout", function(d, i) {
  svg.selectAll("rect.color-" + colors[i].substring(1)).style("stroke", "white");
});

Complete example here.

Comments