I have some plain JavaScript that listens for clicks, and when clicked, four things happen:
When another button is clicked, the opposite happens to the first clicked button, the added class is removed, the "aria-expanded" attribute is reset to "false" and the div is hidden again (set again for CSS) and the "After" text reverts to "Read More".
However, if the same button is clicked a second time, the added class is removed as expected, and the div is hidden again, the "aria-expanded" attribute is not reset to "false". Can anyone explain why and tell me what I should do? (No jQuery, thanks).
const tips = Array.from(document.querySelectorAll('.toggle-button')); tips.forEach((tip) => { tip.addEventListener('click', () => { tips .filter((f) => f !== tip) .forEach((f) => { f.setAttribute('aria-expanded', false); f.classList.remove('form-opened'); }); tip.setAttribute('aria-expanded', true); tip.classList.contains('form-opened'); tip.classList.toggle('form-opened'); }); });
.toggle-button ~ .tips { display: none; } button.toggle-button[aria-expanded="false"]:after { content: "Read more"; } .toggle-button.form-opened ~ .tips { display: block; margin-bottom: 16px; } button.toggle-button[aria-expanded="true"]:after { content: "Close info"; cursor: pointer; } .visually-hidden { border: 0; padding: 0; margin: 0; position: absolute; height: 1px; width: 1px; overflow: hidden; white-space: nowrap; display: inline-block; }
<div class="toggle-box"> <label for="button-1" class="visually-hidden toggle-list">Open or Close info</label><button id="button-1" class="toggle-button" aria-expanded="false"></button> <div class="tips"> Here is some text that is to be revealed </div> </div> <div class="toggle-box"> <label for="button-2" class="visually-hidden toggle-list">Open or Close info</label><button id="button-2" class="toggle-button" aria-expanded="false"></button> <div class="tips"> Here is some text that is to be revealed </div> </div> <div class="toggle-box"> <label for="button-3" class="visually-hidden toggle-list">Open or Close info</label><button id="button-3" class="toggle-button" aria-expanded="false"></button> <div class="tips"> Here is some text that is to be revealed </div> </div>
I've seen some similar queries, but not exactly the same or very old, or they use jQuery.
Clicking a button will only set the
aria-expanded
property of all other buttons to false. You must also toggle the current button's state: