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
This commit is contained in:
@@ -21,19 +21,33 @@
|
||||
|
||||
// Simplest way to make mermaid re-render the diagrams in the new theme is via refreshing the page
|
||||
|
||||
function initThemeButtons() {
|
||||
for (const darkTheme of darkThemes) {
|
||||
document.getElementById(darkTheme).addEventListener('click', () => {
|
||||
const darkBtn = document.getElementById(darkTheme);
|
||||
if (darkBtn) {
|
||||
darkBtn.addEventListener('click', () => {
|
||||
if (lastThemeWasLight) {
|
||||
window.location.reload();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (const lightTheme of lightThemes) {
|
||||
document.getElementById(lightTheme).addEventListener('click', () => {
|
||||
const lightBtn = document.getElementById(lightTheme);
|
||||
if (lightBtn) {
|
||||
lightBtn.addEventListener('click', () => {
|
||||
if (!lastThemeWasLight) {
|
||||
window.location.reload();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', initThemeButtons);
|
||||
} else {
|
||||
initThemeButtons();
|
||||
}
|
||||
})();
|
||||
|
||||
Reference in New Issue
Block a user