Search code examples
htmlaccessibilitywai-arianvda

Dynamically change the role attribute on elements for accessibility purposes


For a form within a german website we are using a textfield with an autocomplete functionality. When the user enters text into the input field, a dropdown with suggestions appears from which he can then choose a suitable option. This behavior must be fully accessible with NVDA via aria- tags.

It works very well when the input has role="combobox". Now, our customer asked if it was possible to have this role set only when there is actually a list of items that can autocomplete the input (which is not always the case) and the list is open. So there should be two cases:

1. No autocomplete available ≅ List not expanded ⇒ role is NOT set

<input type="text">
<div class="dropdown" role="listbox" aria-expanded="false">...</div>

2. Autocomplete available ≅ List is expanded ⇒ role IS set

<input type="text" role="combobox">
<div class="dropdown" role="listbox" aria-expanded="true">...</div>

Setting this attribute via javascript works just fine. Unfortunately NVDA does not pick up this change and ignores the role. It sticks with whatever was set first.

It feels like there is a significant delay or I forgot to send some signal so that the change can be picked up. Can this behavior be achieved or is this not possible? And if not, why is that?


Solution

  • You shouldn't change the role of an element after its creation. In your case, the role combobox is perfectly suitable, even if there isn't always a dropdown list. I'm curious to know why your customer thinks that it's a problem ?

    As a reminder, the basic definition of a combobox is the combination of a text field and a dropdown list. If there is no option in the list or if the list isn't expanded, the combobox behaves exactly like a simple text field.

    It isn't very well specified whether or not the screen reader has to eventually take the role change into account. Most don't at all, or only do in rare and/or quite undefined circumstances. It has actually more chances to not work than to work. Since it isn't at all reliable, you should avoid it altogether.

    Now, for the why they don't, it's difficult to say, but probably that one part of the answer is that screen readers don't necessarily query the accessibility tree for everything all the time. They cache many informations so to keep a reasonable reactiveness to user input.

    The role of an element is typically something normally not expected to change, so it's certainly kept forever, and it's in principle safe to do so. The same reflection can apply to live regions, as ading/removing aria-live attribute after element creation isn't either usually taken into account.