HTML Semantics with ARIA

HTML Semantics with ARIA

The purpose of text in a HTML page can be described by the element used. The button element tells automated machines that the text is a button. But what if there is no element that adequately describes the text? This is what we use ARIA for.

Consider the <select>.

<select>
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
</select>

It adequately describes to automate machines its purpose and it's current state.

Unfortunately for the select element its not customisable.

We could rebuild it with other HTML elements such as div, but automated machines would not understand its purpose or be able to use it.

The solution is to use ARIA.

<div role="listbox" aria-activedescendant="option1" tabindex="0">
  <div id="option1" role="option" aria-selected="true" tabindex="-1">
    Option 1
  </div>
  <div id="option2" role="option" aria-selected="false" tabindex="-1">
    Option 2
  </div>
</div>

Here, the only HTML element that is used is div. Automated machines can operate it due to the ARIA attributes.

role="listbox"

This tells automated machines that this HTML element is a list of items that the user can select from. It is roughly equivalent to <select>.

role="option"

This tells automated machines that this HTML element is something in a listbox that the user can select. It is equivalent to <option>.

aria-activedescendant="option1"

When the user moves their cursor to an option it will have focus. With this attribute we can tell automated machines which option has focus.

aria-selected="true"

When the user clicks on an option it will be selected. This attribute communicates to automated machines which option is selected.

tabindex="0" and tabindex="-1"

The tabindex attribute is used to change the order that elements are selected when the tab key is pressed.

Without the tabindex attribute the automated machine would not be able to navigate to or control the element.

A value of 0 allows elements to be selected with the tab key. If multiple elements have tabindex="0" the user will need to press tab multiple times.

A value of -1 prevents the user selecting the element by pressing tab only. They must instead use the arrow keys. This improves the experience for the user by reducing the number of tab presses required to navigate the page.