Skip to content

Instantly share code, notes, and snippets.

@danielpost
Last active July 9, 2017 03:57
Show Gist options
  • Save danielpost/77a4c038a8361b4c2576bd4886c4d3c9 to your computer and use it in GitHub Desktop.
Save danielpost/77a4c038a8361b4c2576bd4886c4d3c9 to your computer and use it in GitHub Desktop.
Initiate toggle functionality.
<button aria-pressed="false" aria-label="Toggle something">I'm a toggle button!</button>
<button aria-checked="false" role="switch" aria-label="Switch something">I'm a switch!</button>
/**
* Initiate toggle items, such as ARIA buttons.
* @param {string} selector - The selector of the item to target.
* @param {string} attribute - The Boolean attribute to toggle.
* @param {string} [event=click] - The event to target.
*/
function initiateToggleItems(selector, attribute, event = 'click') {
const items = document.querySelectorAll(selector);
items.forEach((item) => {
item.addEventListener(event, function toggleAttribute() {
const isActive = this.getAttribute(attribute) === 'true';
this.setAttribute(attribute, String(!isActive));
});
});
}
initiateToggleItems('[aria-pressed]', 'aria-pressed');
initiateToggleItems('[aria-checked][role="switch"]', 'aria-checked');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment