Search code examples
javascriptsvggoogle-visualizationaccessibilitywai-aria

Set the custom value of the aria-label on a Google chart


I'm using Google Chart's javascript library to build some charts and I wanted to improve their accessibility. My charts are currently being rendered with the ARIA tag attribute like this:

<svg width="500" height="500" aria-label="A chart." style="overflow: hidden;">

It's kind of a default value. I was wondering if anyone knows how to set a custom value for that attribute through the chart configuration.


Solution

  • there are no config options for setting attributes on the chart elements.
    but you could manually change the attribute on the chart's 'ready' event...

    // set attribute
    google.visualization.events.addListener(chart, 'ready', function () {
      var svg = chart.getContainer().getElementsByTagName('svg');
      if (svg.length > 0) {
        svg[0].setAttribute('aria-label', 'CUSTOM LABEL');
      }
    });
    

    see following working snippet...

    google.charts.load('current', {
      packages:['corechart']
    }).then(function () {
      var data = new google.visualization.DataTable();
      data.addColumn('number', 'x');
      data.addColumn('number', 'y');
    
      for (var i = 0; i <= 100; i++) {
        data.addRow([i, ((2 * i) + (((i % 2) === 0) ? i * 2 : i * -2))]);
      }
    
      var options = {
        chartArea: {
          left: 64,
          top: 48,
          right: 32,
          bottom: 48,
          height: '100%',
          width: '100%'
        },
        height: '100%',
        legend: {
          alignment: 'start',
          position: 'top'
        },
        width: '100%'
      };
    
      var chart = new google.visualization.LineChart(document.getElementById('chart'));
    
      // set attribute
      google.visualization.events.addListener(chart, 'ready', function () {
        var svg = chart.getContainer().getElementsByTagName('svg');
        if (svg.length > 0) {
          svg[0].setAttribute('aria-label', 'CUSTOM LABEL');
          console.log(svg[0].outerHTML.substring(0, svg[0].outerHTML.indexOf('>') + 1));
        }
      });
    
      window.addEventListener('resize', function () {
        chart.draw(data, options);
      });
      chart.draw(data, options);
    });
    html, body {
      height: 100%;
      margin: 0px 0px 0px 0px;
      overflow: hidden;
      padding: 0px 0px 0px 0px;
    }
    
    #chart {
      height: 100%;
    }
    <script src="https://www.gstatic.com/charts/loader.js"></script>
    <div id="chart"></div>