SVG Rectangle display HTML title on mouseover

Anwar picture Anwar · Dec 22, 2015 · Viewed 9.4k times · Source

I try to display a tooltip on mouse hover a rectangle. My attempt were using <g> and set a title to it and set a title to the <rect> itself but does not produce any visible output (on Chrome).

HTML

<svg width="200px" height="200px">
  <g title="blue rectangle">
    <rect width="50px" height="50px" fill="blue" x="10px" y="10px"></rect>
  </g>
  <rect width="50px" height="50px" fill="red" x="60px" y="60px" title="red rectangle"></rect>
</svg>

JSFiddle

OBSERVATION

Thanks to @Jacob Gray comment, the problem remains on Chrome (FireFox behaves correctly).

Can anyone point me to the right direction ?

Answer

Paulie_D picture Paulie_D · Dec 22, 2015

There are two methods: using the recommended <title></title> element, and the discouraged title attribute.

The use of the title attribute is discouraged in the W3C spec. It even comes with a warning.

Warning!

Relying on the title attribute is currently discouraged as many user agents do not expose the attribute in an accessible manner as required by this specification (e.g. requiring a pointing device such as a mouse to cause a tooltip to appear, which excludes keyboard-only users and touch-only users, such as anyone with a modern phone or tablet).


However, as mentioned in this answer by Phrogz, SVG actually has an element for that.

MDN: SVG <title> element

Each container element or graphics element in an SVG drawing can supply a title description string where the description is text-only. When the current SVG document fragment is rendered as SVG on visual media, title element is not rendered as part of the graphics. However, some user agents may, for example, display the title element as a tooltip. Alternate presentations are possible, both visual and aural, which display the title element but do not display path elements or other graphics elements. The title element generally improve accessibility of SVG documents

W3C SVG Spec <desc> & <title> elements

<svg width="200px" height="200px">
  <g>
    <title>blue rectangle</title>
    <rect width="50px" height="50px" fill="blue" x="10px" y="10px"></rect>

  </g>
  <rect width="50px" height="50px" fill="red" x="60px" y="60px" title="red rectangle"></rect>
</svg>