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;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment