Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle aria-expanded between true and false with javascript

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');
  }
};

like image 325
Robert E Avatar asked Aug 24 '26 14:08

Robert E


2 Answers

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()}` 
    );
  }
};
like image 109
connexo Avatar answered Aug 27 '26 04:08

connexo


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.

like image 45
Yann Dìnendal Avatar answered Aug 27 '26 03:08

Yann Dìnendal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!