From 10adf2de1f648a5d5d0b4dcf2062ff558cc44c42 Mon Sep 17 00:00:00 2001 From: LD-Reborn Date: Tue, 23 Dec 2025 13:30:19 +0100 Subject: [PATCH] Added accessibleBootstrapToast --- src/javascript/accessibleBootstrapToast.js | 62 ++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/javascript/accessibleBootstrapToast.js diff --git a/src/javascript/accessibleBootstrapToast.js b/src/javascript/accessibleBootstrapToast.js new file mode 100644 index 0000000..7a55a9a --- /dev/null +++ b/src/javascript/accessibleBootstrapToast.js @@ -0,0 +1,62 @@ +/* + + Shows a toast on the bottom right with a given message and notification type (e.g. success, warning, danger) + + How to use: + 1. Copy the functions below into your javascript codebase + 2. Define `window.appTranslations.closeAlert` in your codebase (e.g. _Layout.cshtml) or if you + already have a client-side translation in-place, modify this code to use it. + + You should know: + The base for this code was suggested by AI and refined by me to be accessible. + It helped pass WCAG 2.2 AAA tests in this application: https://github.com/LD-Reborn/Berufsschule_HAM + +*/ + +function createToastContainer() { + const container = document.createElement('div'); + container.id = 'toastContainer'; + container.className = 'toast-container position-fixed bottom-0 end-0 p-3'; + container.setAttribute("aria-live", "polite"); + container.setAttribute("aria-atomic", "true"); + + const liveRegion = document.createElement('div'); + liveRegion.id = 'toastLiveRegion'; + liveRegion.className = 'visually-hidden'; + liveRegion.setAttribute('aria-live', 'assertive'); + liveRegion.setAttribute('aria-atomic', 'true'); + container.appendChild(liveRegion); + + document.body.appendChild(container); + return container; +} + +// Simple toast helper +function showToast(message, type) { + const toastContainer = document.getElementById('toastContainer') || createToastContainer(); + const toast = document.createElement('div'); + toast.className = `toast align-items-center text-white bg-${type} border-0`; + toast.role = 'alert'; + var useDarkElements = type === "warning" + toast.innerHTML = ` +
+
${message}
+ +
+ `; + if (useDarkElements) { + toast.classList.remove("text-white"); + toast.classList.add("text-dark"); + } + toastContainer.appendChild(toast); + + const liveRegion = document.getElementById('toastLiveRegion'); + if (liveRegion) { + liveRegion.textContent = ''; + setTimeout(() => liveRegion.textContent = message, 500); + } + + const bsToast = new bootstrap.Toast(toast, { delay: 10000 }); + bsToast.show(); + toast.addEventListener('hidden.bs.toast', () => toast.remove()); +} \ No newline at end of file