Toggle aria-expanded with ES6 JavaScript
Asked Answered
C

2

2

I am trying to toggle an aria tag between true and false when a button is clicked. I've tried several implementations which seem 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');
  }
};

Capp answered 8/11, 2021 at 19:11 Comment(1)
Does this answer your question? Toggle aria-expanded between true and false with javascriptFebri
I
5

You can toggle the attribute by comparing its value with 'true'.

x.ariaExpanded = x.ariaExpanded !== 'true';
Indoor answered 8/11, 2021 at 19:29 Comment(2)
Wow! That was much simpler then I thought! Thank you. TIL.Capp
@RobertE Happy to help.Indoor
Q
0

When there are a few aria-expanded to set, an inline attribute onclick js can be used:

<details>
    <summary 
        aria-expanded="false" 
        onclick="(() => { this.setAttribute('aria-expanded', this.getAttribute('aria-expanded') === 'true' ? 'false' : 'true'); })()"
        >Details and summary</summary>
    More details…
</details>
Quantize answered 9/7 at 7:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.