Skip to content

Instantly share code, notes, and snippets.

@romaricpascal
Created June 28, 2022 14:29
Show Gist options
  • Save romaricpascal/a6e1176fcefe5536c0b226d4a438aa59 to your computer and use it in GitHub Desktop.
Save romaricpascal/a6e1176fcefe5536c0b226d4a438aa59 to your computer and use it in GitHub Desktop.
Soft disabling using `aria-disabled` rather than `disabled` attribute
/**
* Helper functions for managing button disabling through `aria-disabled`
* rather than the `disabled` attribute, which is less accessible.
* Includes functions for setting the disabled state,
* testing whether an element is disabled and a listener for preventing events
* @module aria_disabled
*/
/**
* @param {HTMLElement} element
*/
export function enable(element) {
element.removeAttribute('aria-disabled');
}
/**
* @param {HTMLElement} element
*/
export function disable(element) {
element.setAttribute('aria-disabled', 'true');
}
/**
* @param {HTMLElement} element
*/
export function isDisabled(element) {
return element.getAttribute('aria-disabled') == 'true';
}
/**
* @param {HTMLElement} element
*/
export function withinDisabled(element) {
return element.closest('[aria-disabled="true"]');
}
/**
* @param {Event} event
* @example
* ```
* document.addEventListener('click', preventEventIfDisabled, true);
* ```
*/
export function preventEventIfDisabled(event) {
// The event's target may be a `<span>` or `<svg>` inside the `<button>`
if (withinDisabled(event.target)) {
// Prevent the browser from doing whatever it would have done
event.preventDefault();
// Prevent other JS code from getting an event,
// making it like the event never happened
event.stopImmediatePropagation();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment