Last active
May 11, 2023 15:55
-
-
Save patrickfox/2b9b3c7d1f413f4e5928e6af6f45228f to your computer and use it in GitHub Desktop.
This script creates functions that add aria-hidden="true" to all elements except for the element specified.
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
// Hide and unhide from assistive technology (AT) | |
const hideFromAT = function(el){ | |
const { body } = document; | |
let currentEl = el; | |
// If there are any nodes with oldAriaHiddenVal set, we should | |
// bail, since it has already been done. | |
const hiddenEl = document.querySelector('[data-original-aria-hidden]'); | |
if (hiddenEl !== null) { | |
// eslint-disable-next-line no-console | |
console.warn('Attempted to run hideFromAT() twice in a row. unhideFromAT() must be executed before it run again.'); | |
return; | |
} | |
do { | |
// for every sibling of currentElement, we mark with | |
// aria-hidden="true". | |
const siblings = currentEl.parentNode.childNodes; | |
for (let i = 0; i < siblings.length; i++) { | |
const sibling = siblings[i]; | |
if (sibling !== currentEl && sibling.setAttribute) { | |
sibling.setAttribute('data-original-aria-hidden', sibling.ariaHidden || 'null'); | |
sibling.setAttribute('aria-hidden', 'true'); | |
} | |
} | |
// we then set the currentEl to be the parent node | |
// and repeat (unless the currentNode is the body tag). | |
currentEl = currentEl.parentNode; | |
} while (currentEl !== body); | |
}; | |
const unhideFromAT = function() { | |
const elsToReset = document.querySelectorAll('[data-original-aria-hidden]'); | |
for (let i = 0; i < elsToReset.length; i++) { | |
const el = elsToReset[i]; | |
const ariaHiddenVal = el.getAttribute('data-original-aria-hidden'); | |
if (ariaHiddenVal === 'null') { | |
el.removeAttribute('aria-hidden'); | |
} else { | |
el.setAttribute('aria-hidden', ariaHiddenVal); | |
} | |
el.removeAttribute('data-original-aria-hidden'); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment