Created
March 14, 2024 15:16
-
-
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).
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
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