Web Accessibility Training
Toronto, Montreal, Ottawa and worldwide via Webex More

How to toggle aria-expanded
and other WAI-ARIA values with JavaScript

WAI-ARIA is not hard from a JavaScript point of view. Most of the time you are just swapping out values of the WAI-ARIA attributes, or toggling them true and false . One such situation is aria-expanded . Surprisingly, there are not many simple tutorials, not even at w3schools that show how to toggle values with JavaScript.

For all those who are not JavaScript programmers, here is some simple code to toggle the value of aria-expanded . There are many ways to do this including using jQuery or other frameworks but this is just simple straight code to show how easy it is to learn to manipulate WAI-ARIA values.

How it works

  • The button element has an aria-expanded that starts as false which would be the case for an expandable hamburger menu.
  • The script looks for the element with id="p2" which is the button with aria-expanded, and saves the value to the variable "x", which is false (not expanded) by default
  • Then we do an if/then operation on the variable "x".
  • if the value is true, then change it to false,
  • if it is false, then change it to true.
  • Finally, it finds the element with id="p2" and inserts the value of "x" which is "true" into the value of aria-expanded
  • and just for our purposes it also dumps that value into the name of the button so we can see it's action.

Try it

Click the button to toggle the aria-expanded value

 

How to do it

<button onclick="myFunction()"  id="p2" aria-expanded="false">Try it</button>
 <script>
  function myFunction() {
  var x = document.getElementById("p2").getAttribute("aria-expanded"); 
  if (x == "true") 
  {
  x = "false"
  } else {
  x = "true"
  }
  document.getElementById("p2").setAttribute("aria-expanded", x);
  }
</script>

NOTE: I also added the line to display the value in the button but that is not necessary to toggle it.

document.getElementById("p2").innerHTML = "aria-expanded =" + x;

See also This example

Feel free to comment on Twitter @davidmacd

Author information:

David MacDonald is a veteran WCAG member, co-editor of Using WAI ARIA in HTML5 and HTML5 Accessibility Task Force Member. Opinions are my own.




CONTACT US

For a quote or just to chat about your organization's needs


EMAIL

help at can hyphen adapt dot com, (spoken phonetically to trick spam bots)

PHONE

six one three, eight zero six, nine zero zero five

SOCIAL MEDIA