Toggle aria-expanded between true and false with javascript
Asked Answered
F

3

6

I am trying to toggle an aria tag between true and false when a button is clicked. I've tried several implementations which seems to do absolutely nothing. Below is what I am currently using which successfully toggles the class. How can I extend this to toggle the aria-expanded value between true and false? Be easy on me, I am transitioning from jQuery to ES6.

const theTrigger = document.getElementById('mobile-form-control');
const theForm = document.querySelectorAll('.l-header__mobile-form');

theTrigger.onclick = function () {
  for (const x of theForm) {
    x.classList.toggle('show');
  }
};

Fouts answered 8/11, 2021 at 18:39 Comment(3)
I pasted the wrong bit of code :/ I've updated my question.Fouts
ARIA attributes are no different than other HTML attributes and can be changed with setAttribute() as @connexo recommended.Charterhouse
On StackOverflow, you are required to manage your questions' lifecycle. That means, that if you get answers, and they solve your problem, pick the answer that answers it best. If not, comment on the answers given and explain why these do not help you solve your problem.Gentes
L
11

As of Firefox 119, you can use the ariaExpanded API to toggle true/false on that attribute:

x.ariaExpanded = x.ariaExpanded !== 'true';

NOTE: ariaExpanded returns a string, so you cannot use the logical NOT (!) operator by itself.

Lisk answered 8/6, 2022 at 9:30 Comment(2)
While this syntax didn't work for my specific situation (ariaExpanded returns a string), a very similar syntax in a similar question did. TIL ariaExpanded! So happy we have that now.Pulverable
@adam-johnson: Thanks, you are right! I edited my answer with the correct fix.Silage
G
10

Assuming x in your for-loop is the element you want to toggle the aria-expanded attribute on:

theTrigger.onclick = function () {
  for (const x of theForm) {
    x.classList.toggle('show');
    x.setAttribute(
      'aria-expanded', 
      `${(x.getAttribute('aria-expanded') !== 'true').toString()}` 
    );
  }
};
Gentes answered 8/11, 2021 at 20:2 Comment(1)
This should be marked as the right answer!Sher
V
0

An inline attribute onclick js can be used when there are a few aria-expanded to set:

<details>
    <summary 
        aria-expanded="false" 
        onclick="(() => { this.setAttribute('aria-expanded', this.getAttribute('aria-expanded') === 'true' ? 'false' : 'true'); })()"
        >Click on summary</summary>
    The content of the details…
</details>
Vermin answered 9/7 at 7:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.