Home > Back-end >  D3 tooltip not following the mouse
D3 tooltip not following the mouse

Time:10-13

I have created a webpage with multiple charts using D3 and Object Oriented Programming.

Working code link--> enter image description here enter image description here enter image description here

CodePudding user response:

The underlying problem is addressed here but the answer doesn't directly solve your problem. Basically, there's a second and optional argument to d3.pointer called target such that:

If target is not specified, it defaults to the source event’s currentTarget property, if available. If the target is an SVG element, the event’s coordinates are transformed using the inverse of the screen coordinate transformation matrix...

You can make use of this argument per below noting that it will break your vertical tracking line if you try and just update vis.mouse:

// mouse moving over canvas
vis.mouse = d3.pointer(event); // keep this for the vertical tracking line
vis.mouse2 = d3.pointer(event, d3.select(vis.chartLocation)); // <--- NEW VARIABLE!

Now vis.mouse2 has a relative x and y - so use them where you set the style of the div:

d3
  .select(vis.chartLocation)
  .selectAll("#tooltip")
  .html((d, i) => {
    vis.xDate = d.values[vis.idx - 1].date;
    return vis.xDate.toLocaleDateString("pt-PT");
  })
  .style("display", "block")
  .style("left", vis.mouse2[0]   "px") // use vis.mouse2
  .style("top", vis.mouse2[1]   "px") // use vis.mouse2

The clue is in that your first selection is vis.chartLocation.

  • Related