2

I have an svg embedded in HTML using an object tag

<div id="svgDiv">
<object id="svgObjectElement" data="mysvg.svg" type="image/svg+xml">
            Your browser doesn't support SVG.
</object>
</div>

I want to use the tippy.js library to provide tooltips for circles in my svg, but I can't seem to get tippy to use the circles in mysvg as targets. If the svg is in the HTML (like this line element) it works great.

HTML:

<svg height="50" width="50"><line x1="0" y1="0" x2="50" y2="50" style="stroke:tomato;stroke-width:5"></line></svg>
<div id="svgDiv">
<object id="svgObjectElement" data="mysvg.svg" type="image/svg+xml">
            Your browser doesn't support SVG.
</object>
</div>

JavaScript:

tippy('line', {
    content: 'Custom Line Tooltip',
})

I have tried the following JavaScript where circle1 is the id of a circle in the svg but it doesn't work:

var svgDocument = document.getElementById("svgObjectElement").contentDocument;
var element = svgDocument.getElementById("circle1");
tippy(element, {
    content: 'Custom circle Tooltip',
});

I have also tried

var svgDocumentElement= document.getElementById("svgObjectElement").contentDocument.documentElement;
var element = svgDocumentElement.getElementById("circle1");
tippy(element, {
    content: 'Custom circle Tooltip',
});

which doesn't work. I am using Chrome if that is relevant. Any ideas would be appreciated.

P.Ellis
  • 55
  • 2
  • 10

1 Answers1

0

As far as I understand, Tippy.js temporarily appends a div element at the end of body tag, inside body tag itself. The problem with svg elements is that they neither have body tag nor they support the div tag and are therefore not going to show up. See here: Is it possible to append a div inside an SVG element?

If Tippy.js were able to detect that it is inside an svg document it could wrap the div inside foreignobject tag (which would most probably solve the issue).

One more thing to notice is that you would also have to include Tippy.js library directly into the svg document itself like this <script xlink:href="../js/tippy.min.js"></script>. But even then you will get an error because Tippy.js is trying to reference elements which do not exist head, body, etc.

So, to me, the best approach for this problem is to create an overlay div over your circle1 element outside of the svg object and add a tooltip to that div. Hint: How to overlay one div over another div

Emir
  • 380
  • 3
  • 11