From faa30b9285e33aad6ff596b6e7896bd34594fb62 Mon Sep 17 00:00:00 2001 From: Bryce Date: Thu, 19 Mar 2026 20:14:58 -0700 Subject: [PATCH] Fix: Check if theme button elements exist before adding event listeners The mermaid-init script was throwing 'Uncaught TypeError: can't access property addEventListener, document.getElementById(...) is null' because it tried to attach click handlers to theme toggle buttons (ayu, navy, coal, light, rust) that may not exist on all pages. Fixed by: - Wrapping theme button event listener registration in null checks - Using DOMContentLoaded fallback when document is still loading - Keeping mermaid.initialize() call outside the check since it needs to run early with startOnLoad: true --- mermaid-init.js | 36 +++++++++++++++++++++++++----------- 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/mermaid-init.js b/mermaid-init.js index 0469ff1..8a110ca 100644 --- a/mermaid-init.js +++ b/mermaid-init.js @@ -21,19 +21,33 @@ // Simplest way to make mermaid re-render the diagrams in the new theme is via refreshing the page - for (const darkTheme of darkThemes) { - document.getElementById(darkTheme).addEventListener('click', () => { - if (lastThemeWasLight) { - window.location.reload(); + function initThemeButtons() { + for (const darkTheme of darkThemes) { + const darkBtn = document.getElementById(darkTheme); + if (darkBtn) { + darkBtn.addEventListener('click', () => { + if (lastThemeWasLight) { + window.location.reload(); + } + }); } - }); + } + + for (const lightTheme of lightThemes) { + const lightBtn = document.getElementById(lightTheme); + if (lightBtn) { + lightBtn.addEventListener('click', () => { + if (!lastThemeWasLight) { + window.location.reload(); + } + }); + } + } } - for (const lightTheme of lightThemes) { - document.getElementById(lightTheme).addEventListener('click', () => { - if (!lastThemeWasLight) { - window.location.reload(); - } - }); + if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', initThemeButtons); + } else { + initThemeButtons(); } })();