Last active
July 9, 2017 03:57
-
-
Save danielpost/77a4c038a8361b4c2576bd4886c4d3c9 to your computer and use it in GitHub Desktop.
Initiate toggle functionality.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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