Use ARIA Attributes for JavaScript State Setting & Styling

In other words, making lots of friends with one gift

Mark Caron
2 min readSep 9, 2016

Picture this: you’re a web developer tasked with writing a simple JavaScript component that will expand and collapse a panel of content at the click of a button.

We’ve all seen these before, right?

However, this time you decide to break away from the convention of adding classes like “expanded” or “collapsed” to the panel and the button. You’re tired of the CSS classitisthat disease that’s plaguing the web. Instead, you’re feeling saucy and you reach into the WebAIM bag of tricks for some semantic ARIA labels. Why not, right? You know that the web standards nut on your team is going to nag you to put them in your app anyway (that person can be so annoying sometimes). Plus, it’s possible to style the application using CSS attribute selectors, and they have the same specificity as classes.

So, you write the HTML:

Figure 1: ARIA-based Toggling HTML

Then you write the JavaScript:

Figure 2: ARIA-based Toggling JavaScript

And then the CSS is simple:

Figure 3: ARIA-based Toggling CSS

Try it out for yourself!

Now you’ve made lots of friends with the simple gift of ARIA attributes. Your component is now more accessible — your users will love you — and that web standards nut will thank you for not forcing them to nag.

Benefits to this method

  1. As simple and as fast as the typical method of applying/removing classes.
  2. Better accessibility built-in from the start.
  3. More semantic since ARIA attributes provide meaning.
  4. Less CSS noise or classitis.

Comments & feedback

As always, I am interested to hear everyone’s thoughts and feedback on this technique as well as accessibility in general.

--

--

Mark Caron

UX / DesignOps Manager at Red Hat. Obsessed with soccer, web standards & accessibility, and tacos.