'Make Screen Reader read out a prefix text along with DOM contents when using role=option
I have an outer div of role="listbox" and a few inner divs of role="option".
When I use keyboard up-down to move focus within the elements of the inner div, it reads them out as "1 of 5, Element 1", "2 of 5, Element 2", "3 of 5, Element 3" and so on..
I am looking to have it read a prefix text such as "Prefix text" prior to it reading out the element, so it reads as "Prefix text, 1 of 5, Element 1", "Prefix text, 2 of 5, Element 2" and so on..
I have tried adding an aria-label="prefix text" to the outer div but it doesn't help.
I have a codesandbox here showing the DOM structure - https://codesandbox.io/s/narrator-option-example-eb8ghh?file=/index.html
Solution 1:[1]
First clarifying question, when you say you use the up-down arrow key, is that with or without a screen reader running? Because up-down when a screen reader is running moves the screen reader focus to the next DOM element but up-down without the screen reader will scroll the page unless you are trapping on that keyboard event.
I ask because your code sample doesn't seem to handle keyboard events so without a screen reader running, I can't navigate to the listbox items.
However, with that being said, you can trick the screen reader into saying prefix text but not display the prefix text using a CSS content property.
In your demo code, add this:
<style>
div[role=option]::before {content: "prefix text";font-size: 0px;}
</style>
Setting the font size to 0 makes it invisible but the screen reader still announces it. It works with NVDA, JAWS, and Voiceover.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | slugolicious |
