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...
Selecting the tooltipMake sure the script element appears as the last element in the SVG, so the tooltip <text> element exists when the script is run. The code will be the same if you put the JS in a separate file, so long as the SVG is inline, otherwise see my SVG + JS tutorial for how to access the SVG document.
The title attribute is placed on the <svg> opening tag. The value can be any string. Hover over the svg and a tooltip appears.
The <title> tag for an SVG should be brief, much like an alt attribute for an image. In the SVG tag, include an aria-labelledby attribute that points to the <title> tag. If there is more than one shape, it can be a good idea to include a title tag for each shape group.
The title attribute specifies extra information about an element. The information is most often shown as a tooltip text when the mouse moves over the element. The title attribute can be used on any HTML element (it will validate on any HTML element.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With