Search code examples
javascriptcssreactjsd3.jsonmouseover

How to hover over one chart to display a vertical line and tooltip on all charts in D3.js?


I'm using D3.js with ReactJS I want to hover over one chart and display a vertical line and tooltip on all the other charts.

I'm able to get vertical line in only one chart at a time. The expected result is to display a vertical line and tooltip across all charts.

this what I tried:

  React.useEffect(() => {
    d3.select(anchorEl)
      .on("mouseout.tooltip", () => {
        d3.select(ref.current).attr("opacity", 0);
      })
      .on("mouseover.tooltip", () => {
        d3.select(ref.current).attr("opacity", 1);
      })
      .on("mousemove.tooltip", (e) => {
        d3.select(ref.current)
          .selectAll(".tooltipLinePoint")
          .attr("opacity", 1);
        followPoints(e);
      });
  }, [anchorEl, followPoints]);

This is the actual code result multiline-chart-tooltip-acoss-all-charts


Solution

  • The solution:

    Draw the line for the current hovered chart and then draw the line for the others charts and the key is to use d3.select() and d3.selectAll().

      d3.select(ref.current)
        .select(".tooltipLine")
        .attr("x1", x)
        .attr("x2", x)
        .attr("y1", -margin.top)
        .attr("y2", height);
    
      d3.selectAll(".tooltip")
        .select(".tooltipLine")
        .attr("x1", x)
        .attr("x2", x)
        .attr("y1", -margin.top)
        .attr("y2", height);
    
      drawLine(baseXPos);
      drawContent(baseXPos);
      drawBackground();
    
      drawLineForOthers(baseXPos);
      drawContentForOthers(baseXPos);
      drawBackgroundForOthers();