Extending an SVG tooltip's hover zone out of its parent element's bounds

Viewed 619

I have a chart SVG that contains some elements that have tooltips attached. The tooltips are HTML embedded using foreignObject and are supposed to be shown when hovering on those elements. I gave the SVG overflow: visible to make sure tooltips could be fully displayed.

This works fine, but the problem is that as soon as the cursor leaves the bounds of the outer SVG, the tooltip disappears:

SVG tooltip

(The SVG ends just below the bottom axis)

Is there a way to "extend" the hover zone to include any element that sticks out of the SVG like this?

2 Answers

This is an example of how to an element outside the SVG as a tool tip:

let mouse = {};
let tooltip = document.querySelector("#tooltip");
svg.addEventListener("mousemove", e => {
  tooltip.innerHTML = "";
  if (e.target.tagName == "circle") {
    mouse = oMousePos(svg, e);
   
    tooltip.innerHTML = e.target.id;
    tooltip.style.left = mouse.x + "px";
    tooltip.style.top = mouse.y + "px";
  }
});

function oMousePos(svg, evt) {
  var ClientRect = svg.getBoundingClientRect();
  return {
    //objeto
    x: Math.round(evt.clientX - ClientRect.left),
    y: Math.round(evt.clientY - ClientRect.top)
  };
}
svg{border:1px solid;}
circle{fill:gold;}
#tooltip{position:absolute;padding:1em; }
<article>
<svg id="svg" viewBox="0 0 100 50">
 <circle id="c1" cx="56" cy="17" r="15" />
 <circle id="c2" cx="23" cy="34" r="7" />
</svg>

<div id="tooltip"></div>
</article>

One solution I was given was to give the SVG a large 100px transparent border-bottom and background-clip: padding-box (although in my case that second part wasn't even necessary).

It's not perfect because it relies on a fixed border width and will break if a tooltip is taller than that, but it does extend the hover zone so it's one option.

Related