Reputation: 24406
I have an svg:circle with an svg:title element under it such that the title is displayed as a tooltip for the circle. How can I programmatically (using javascript) show and hide this tooltip?
Upvotes: 1
Views: 434
Reputation: 15371
As the title element itself can't be shown programmatically, you'd have to create a <text>
element and position it appropriately. As text does not have background, you either need to create a <rect>
as background or use a filter to draw a background. Also, there is currently no reliable cross-browser line wrapping (unless you'd be using an HTML <foreignObject>
).
So, here's a rough suggestion as a starting point:
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">
<filter x="0" y="0" width="1" height="1" id="tooltipBackground">
<feFlood flood-color="rgba(200,200,200,.5)"/>
<feComposite in="SourceGraphic"/>
</filter>
<circle r="50" cx="100" cy="100">
<title>my tooltip</title>
</circle>
<script type="text/javascript">
function showCircleTooltip(circle) {
var title = circle.getElementsByTagName("title")[0];
if (title) {
var tooltip = document.createElementNS("http://www.w3.org/2000/svg","text");
tooltip.textContent = title.textContent;
tooltip.setAttribute("filter","url(#tooltipBackground)");
// We're putting the tooltip at the same place as the circle center.
// Modify this if you prefer different placement.
tooltip.setAttribute("x",circle.getAttribute("cx"));
tooltip.setAttribute("y",circle.getAttribute("cy"));
var transform = circle.getAttribute("transform");
if (transform) {
tooltip.setAttribute("transform",transform);
}
circle.parentNode.insertBefore(tooltip, circle.nextSibling);
}
}
showCircleTooltip(document.getElementsByTagName("circle")[0])
</script>
</svg>
Upvotes: 1