Search code examples
htmlaccessibilityscreen-readers

How to make website content that appears and disappears based on user selection accessible to screen readers


In HTML, I have a select element that users can choose options from. Based on their choice, different content appears elsewhere on the page. In pseudocode (because I don't want the question to be framework specific):

<select>
<option>CHOOSE YOUR OPTION</option>
<option>A</option>
<option>B</option>
</select>

<div id='A' style="display: currentSelection === 'A' ? 'block' : 'none' ">
You selected A
</div>
<div id='B' style="display: currentSelection === 'B' ? 'block' : 'none' ">
You selected B
</div>

The change from display: none to display: block is handled by javascript when the select element changes value.

I want the content under #A and #B not to be read out by a screen reader unless their respective options are selected. I.e. the behaviour of the screen reader to ignore display:none elements is correct. But how can I make sure that the content is read out when the css display value changes to something visible?


Solution

  • Put your two <div> elements in separate live regions. Elements that are unhidden that are inside live regions will be announced by the screen reader.

    <div aria-live="polite">
      <div id='A' style="display:none">
      You selected A
      </div>
    </div>
    
    <button onclick="document.getElementById('A').style.display = 'block'">foo</button>