16

I would like to change the default appearance of tooltip in svg elements (title) by any means such as js or css.

I even tried stuff like this:

var title = document.createElementNS('http://www.w3.org/2000/svg','title');
title.textContent='<foreignObject width="100" height="50" requiredExtensions="http://www.w3.org/1999/xhtml"><div style="background:blue;">'+arr[j].ypos+'</div><foreignObject>';
rect.appendChild(title);

but regardless of whatever i insert as the textContent of title, its simply rendered as a string.

Is there any way to style the default tooltip? Other simple and straightforward alternatives for creating tooltips in svg without using any plugins are also welcome...

T J
  • 42,762
  • 13
  • 83
  • 138

1 Answers1

12

You could try this: How to change the style of Title attribute inside the anchor tag?. I didn't test it, so I don't really know if it works.

But since you are using SVG, you can do better than that since you can draw tooltips with any color and shape, even animated. Since you are generating it dynamically with a script, you can calculate the size based on the content and alter the height and width accordingly.

Here is an example of a tooltip using a rounded rectangle in SVG:

<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
    <g id="component">
        <rect id="content" width="50" height="50">
        </rect>
        <g class="tooltip" transform="translate(20,20)" opacity="0.9">
            <rect rx="5" width="100" height="25"></rect>
            <text x="15" y="16">Hello</text>
        </g>
    </g>
</svg>

I used CSS hover to make it appear and disappear:

#component .tooltip {visibility: hidden}
#component:hover .tooltip {
    visibility: visible;
}
.tooltip text {
    fill: black;
    font-size: 12px;
    font-family: sans-serif;
}
.tooltip rect {
    fill: yellow;
    stroke: blue;
}

You can experiment with it in this JSFiddle.

You can also store your tooltips in a <defs> block and reuse it in different objects.

Dmitry
  • 6,716
  • 14
  • 37
  • 39
helderdarocha
  • 23,209
  • 4
  • 50
  • 65
  • 3
    This is nifty visually, but it seems like by not using actual tags you're lessening the accessibility of your SVGs, aren't you? There are tooltips and then there is alternative text for the visually impaired. Two different things. https://www.sitepoint.com/tips-accessible-svg/ – steev Apr 09 '19 at 00:04
  • 1
    You could have both, adding `title` to `` and disabling pointer events on it (`rect {pointer-events: none}`). The title attribute can still be read, but it won't show as a tooltip on hover since the `rect` won't capture events, but the parent `#container` will, showing a tooltip on hover. – helderdarocha May 16 '19 at 19:04
  • not answer the `title` question at all. https://i.stack.imgur.com/lBzc7.png – xgqfrms Aug 31 '23 at 12:36