I have a chart (Highcharts) written in a React application with custom formatted tooltips; however, screen readers will not announce the tooltip content when 'tabbed' through the points.
I wrote some JavaScript that solves my problem and announces the tooltips on mouseOut as they should be announced without creating unnecessary elements in the DOM.
point: {
events: {
mouseOut: function () {
let ariaText = this.category + ', Projected Savings: $ ' + this.projectedSavingsFormatted + ', Target Savings: ' + targetSavingsFormatted + ', Time to Achieve: ' + this.timeToAcheive + ' months';
let tooltips = document.querySelectorAll('div.highcharts-tooltip')[0];
tooltips.getElementsByTagName('span')[0].setAttribute('role', 'tooltip');
tooltips.getElementsByTagName('span')[0].setAttribute('aria-live', 'assertive');
tooltips.getElementsByTagName('span')[0].setAttribute('aria-label', ariaText);
}
}
}
My question is this: How do I clean this up? There has to be a more efficient way to write this function.
If you want to get just a single element, use querySelector(…)
instead of querySelectorAll(…)[0]
:
let tooltips = document.querySelectorAll('div.highcharts-tooltip')[0];
// becomes:
let tooltips = document.querySelector('div.highcharts-tooltip');
But, based on your code, it seems there is no need to select the div
– if you just want the first span
, select it right away, without storing the parent node:
let tooltip = document.querySelector('div.highcharts-tooltip span');
tooltip.setAttribute('role', 'tooltip');
tooltip.setAttribute('aria-live', 'assertive');
tooltip.setAttribute('aria-label', ariaText);
To save few characters and hopefully make the long string clearer, you can use template literals instead of chaining '…' + … + '…'
:
let ariaText = this.category + ', Projected Savings: $ ' + this.projectedSavingsFormatted + ', Target Savings: ' + targetSavingsFormatted + ', Time to Achieve: ' + this.timeToAcheive + ' months';
// becomes:
let ariaText = `${this.category}, Projected Savings: $ ${this.projectedSavingsFormatted}, Target Savings: ${targetSavingsFormatted}, Time to Achieve: ${this.timeToAcheive} months`;
// notice the backticks (``) instead of quotes ('')
So, your function could become:
point: {
events: {
mouseOut: function () {
let ariaText = `${this.category}, Projected Savings: $ ${this.projectedSavingsFormatted}, Target Savings: ${targetSavingsFormatted}, Time to Achieve: ${this.timeToAcheive} months`;
let tooltip = document.querySelector('div.highcharts-tooltip span');
tooltip.setAttribute('role', 'tooltip');
tooltip.setAttribute('aria-live', 'assertive');
tooltip.setAttribute('aria-label', ariaText);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.