skip to Main Content

I have an SVG with a title element, as well as polygons with their own empty titles in the hopes of preventing the parent title from appearing when hovering over the polygons because I have a custom JavaScript tooltip for the polygons. So something like

<svg aria-labelledby="title1">
<title id = "title1">My big title</title>
<polygon aria-labelledby="title2"></polygon>
// this title element is dynamically generated by JS after the rest of the SVG is added to page
<title id="title2"></title>
</svg>

The SVG is generated dynamically from a library and I use JavaScript to append the blank title to remove the main title tooltip from polygons, but after running the JavaScript the tooltip still appears even though the new blank titles are in the DOM.

If I go into the developer tools and edit HTML, but make no changes and then hover over the polygons only the custom tooltip displays as expected. It seems that the JavaScript code adds the blank titles but the browser is cacheing the previous aria data state. Is there any way to use JavaScript to force the browser to reevaluate the aria metadata? I’ve tried basic things like adding and removing classes

2

Answers


  1. You can reinsert the SVG in the dom:

    const svg = document.querySelector("svg");
    const clone = svg.cloneNode(true);
    svg.parentNode.replaceChild(clone, svg);
    

    Or do remove and add on the parent.

    A minimal reproducible would be nice for further investigation.

    Login or Signup to reply.
  2. There seem to be two misunderstandings in the question, if I got the question right.

    1. ARIA attributes like aria-labelledby do not change browser behaviour like tooltips. They only control what gets exposed to assistive technology via the accessibility tree.
    2. You can not have several <title> attributes inside one element¹.

    To give a SVG graphics element a title, the <title> element needs to be it’s child.

    I also recommend leaving out the aria-labelledby attribute for the SVG document, it’s redundant, as the title’s very purpose is to provide an accessible name already.

    The ‘title’ child element represents a short text alternative for the element.

    const emptyTitle = document.createElementNS('http://www.w3.org/2000/svg', 'title');
    emptyTitle.textContent = "";
    
    document.querySelectorAll('circle, rect').forEach(el => el.prepend(emptyTitle.cloneNode()));
    html,
    body,
    svg {
      height: 100%;
    }
    <svg viewBox="0 0 20 10" xmlns="http://www.w3.org/2000/svg">
      <title>Parent Title</title>
      
      <circle cx="5" cy="5" r="4">
      </circle>
    
      <rect x="11" y="1" width="8" height="8">
      </rect>
    </svg>
    1. You might have several <title> siblings only in a single case:

    Multiple sibling ‘desc’ or ‘title’ elements must have different languages

    the SVG specification

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search