DEV Community

Cover image for A11y tips: alert role
Carlos Espada
Carlos Espada

Posted on

A11y tips: alert role

The other alternative for notifying content changes is to use role="alert", which is equivalent to using aria-live="assertive" together with aria-atomic="true". So...

<div aria-live="assertive" aria-atomic="true">
  <h3>Your message has been sent. We'll contact you back as soon as possible.</h3>
</div>
Enter fullscreen mode Exit fullscreen mode

... is equivalent to this ...

<div role="alert">
  <h3>Your message has been sent. We'll contact you back as soon as possible.</h3>
</div>
Enter fullscreen mode Exit fullscreen mode

Being equivalent to using an aria-live="assertive", and therefore causing the immediate interruption of the user, the alert role should only be used for information that requires the user's immediate attention, for example:

  • An invalid value was entered into a form field
  • The user's login session is about to expire
  • The connection to the server was lost so local changes will not be saved

There are several aspects to note when using the alert role:

  • Since it is not possible to change the predefined role of an element, it is ideal to use role="alert" in a <div> or in a <span>.
  • Unlike the method in the previous post, it can be used with elements that are not initially present in the DOM. When inserted with role="alert" they will be announced immediately.
  • The element with the alert role does not have to be able to receive focus, as screen readers will automatically announce the updated content regardless of where keyboard focus when the role is added. So the alert role should only be used for static text content.
  • The alert role is added to the node containing an alert message, not the element causing the alert to be triggered.

If you want to know more, you can find more interesting information on the MDN page.

Discussion (0)