9

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>
DesVal
  • 183
  • 1
  • 1
  • 9

2 Answers2

21

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>
Robert Longson
  • 118,664
  • 26
  • 252
  • 242
1

i tried your code but it doesn't work (Chrome). Then i found in this site a post about tooltip:

How to add a tooltip to an svg graphic?

so instead of add the title attribute, you need to do like this:

<rect id="1" x="0" y="0" fill="#666666" width="20" height="20"><title>"There's some text"</title/></rect>

UPDATE

you can change the text and style with javascript and jquery

Example:

$("#1").find("title").html("Text") 
Community
  • 1
  • 1
ViROscar
  • 148
  • 1
  • 11
  • Thanks. But is there any way how to style these? – DesVal Jan 23 '15 at 14:25
  • also check out this post about css native tooltip: http://stackoverflow.com/questions/9927640/styling-native-tooltip-from-title-tooltip-text – ViROscar Jan 23 '15 at 14:36
  • You can change the html of title but styling doesn't work: `$("#1").find("title").css("color", "red")` – DesVal Jan 23 '15 at 14:47
  • Anyway thanks for help. This is probably not the right solution. I think I'm gonna have to use some plugin for that. – DesVal Jan 23 '15 at 14:49
  • you cannot style the default tooltip, but the previous link shows an alternative. – ViROscar Jan 23 '15 at 15:00