Search code examples
htmlcsssvgtooltiptitle

Adding tooltip to SVG rect tag


What's the best solution for adding tooltip to <rect>?

I've created SVG map with several <rect> tags and I'd like to show tooltip on mouseover. Using title attribute is fine but is there any option how to restyle it using CSS/Javascript/jQuery or is there even better option for adding tooltip?

<svg version="1.1" baseProfile="basic" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 50 50" xml:space="preserve">
    <g>
        <rect id="1" title="There's some text" x="0" y="0" fill="#666666" width="20" height="20"/>
        <rect id="2" title="There's another text" x="30" y="0" fill="#666666" width="20" height="20"/>
    </g>
</svg>

Solution

  • SVG uses title elements, not attributes, you can't style them though. If you need styling you'd need to create the title dynamically as a <text> element and place it at the right location using javascript.

    This is what default tooltips look like...

    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 50 50" xml:space="preserve">
        <g>
            <rect id="1" fill="#666666" width="20" height="20">
              <title>There's some text</title>
            </rect>
            <rect id="2" x="30" fill="#666666" width="20" height="20">
              <title>There's another text</title>
            </rect>
       </g>
    </svg>