Search code examples
d3.jsanchornvd3.jssection508

insert anchor element before every bar column ti make it tabbable


I am trying to make my chart 508 compliant. Hence in order to make it possible to navigate the chart using keyboard, i want to add anchor elements before every bar column. I tried doing :

d3.select("svg").insert("a",".nv-bar").attr("href","");

but it didnt work. Can anybody suggest a better way of doing it. Thanks !


Solution

  • Here's one way to do it:

    d3.selectAll('.nv-bar')
      .each(function() {
        var el = this;
        d3.select(el.parentNode)
          .insert('a', function(){return el;})
          .attr('href', '');
      });
    

    The insert method will add elements to each item in the current selection, regardless of how many elements the "before" parameter matches.

    My solution will add an anchor for each bar in the document, and takes advantage that the insert method can accept a selector string or a function that returns an element to insert before. (Although, somewhat frustratingly, it does not accept a DOM node directly)

    Edit: Here's a jsfiddle with an example: https://jsfiddle.net/bgp6atzo/