ARIA 101
ARIA can be used to add extra accessibility information to tags. It's how we would add
accessibility to a plain div that is trying to emulate a select or other tag. So in general, you
will mostly avoid ARIA unless you are trying to create custom versions of native elements. But,
there are instances that ARIA can be used to enhance native HTML. Here, we'll cover 3 key ARIA
attributes: aria-controls
, aria-expanded
, and aria-label
.
3a: Aria controls and aria-expanded
Imagine that you are building a navigation for a shopping website, and when you hover over the
shop link, you want a dropdown of some options to appear: t-shirts, pants, socks etc. Once you
have built the dropdown menu, you need a way to communicate this relationship of link to dropdown
to a screen reader. With aria-controls
, we are saying to the screen reader “This link
controls this element with this id” — the element in this example being the dropdown menu. aria-expanded
says “if I am true then the dropdown is showing, if I am false then it is
not.” Here is a code snippet that demonstrates this.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ARIA Example</title>
</head>
<body>
<a href="#" id="shopLink" aria-controls="dropdown" aria-expanded="false">Shop</a>
<ul id="dropdown" style="display:none;">
<li>T-shirts</li>
<li>Pants</li>
<li>Socks</li>
</ul>
<script>
document.getElementById('shopLink').addEventListener('mouseover', function() {
const dropdown = document.getElementById('dropdown');
const expanded = this.getAttribute('aria-expanded') === 'true';
dropdown.style.display = expanded ? 'none' : 'block';
this.setAttribute('aria-expanded', expanded ? 'false' : 'true');
});
</script>
</body>
</html>
Aria Label
If you've ever had a window popup when on a website, you'll have likely seen the common convention
of an "X" button in the top corner of the popup that will close the popup upon being clicked. For
a screen reader, it wouldn't be able to decipher what the image of an "X" would be. It would
therefore have no meaning and just be some button. It would be useful if we could have a message
for screen readers that will say that this button closes the window. This is where we'd use aria-label
. This is nice and simple. Just add the aria-label
attribute to
your element and fill it in with text such as “Close Popup.”