Skip to content

Instantly share code, notes, and snippets.

@patrickfox
Created March 14, 2024 15:16
Show Gist options
  • Save patrickfox/1f6a40b9c7bfad7b6771623d29598809 to your computer and use it in GitHub Desktop.
Save patrickfox/1f6a40b9c7bfad7b6771623d29598809 to your computer and use it in GitHub Desktop.
Utility function that enables the announcement of custom messages in order to improve the accessible experience (AX).
export const ariaAnnounce = (message: string, manners = 'assertive'): HTMLElement => {
let announceTimeout: ReturnType<typeof setTimeout> | null;
announceTimeout = null;
let announcer: HTMLElement | null = document.querySelector('#announce-this');
const clearAnnouncer = (): HTMLElement => {
if (announcer) {
announcer.setAttribute('aria-live', 'off');
announcer.innerHTML = '';
}
announceTimeout = null;
return announcer as HTMLElement;
};
const addAnnouncer = () => {
if (announcer) {
announcer.setAttribute('aria-live', manners);
announcer.setAttribute('aria-atomic', 'true');
announcer.innerHTML = message;
}
};
if (!announcer) {
announcer = document.createElement('div');
announcer.id = 'announce-this';
document.body.append(announcer);
}
clearAnnouncer();
addAnnouncer();
if (announceTimeout !== null) {
clearTimeout(announceTimeout);
}
announceTimeout = setTimeout(clearAnnouncer, 2000);
return announcer;
};
@patrickfox
Copy link
Author

This script:

  • Initiates a function ariaAnnounce(msg, manners) that allows developers to pass in a message to be announced to vision impaired screen reader (SR) users
  • Upon first call, create an announcer live region element that is appended to the DOM
    • Note: this element should be visiblyhidden/sronly. Style are not provided in this example.
  • When the ariaAnnounce function is called, the message is added to the announcer live region, which will cause the SR to announce the message.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment