ensure the toggle theme click event listener is only added once

This commit is contained in:
Reorx 2022-06-01 17:42:42 +08:00
parent 07c4add7be
commit b67d5df2e0
2 changed files with 11 additions and 3 deletions

View File

@ -34,10 +34,11 @@
return;
}
let button = document.getElementById("theme-toggle")
// remove the listeners first to prevent adding duplicated listener when history goes back and forth
button.removeEventListener('click', toggleThemeListener)
// listen to toggle button
document.getElementById("theme-toggle").addEventListener("click", () => {
window.dispatchEvent(new CustomEvent('toggle-theme'));
});
button.addEventListener('click', toggleThemeListener)
})();
</script>

View File

@ -48,6 +48,13 @@ window.addEventListener('toggle-theme', function() {
toggleThemeCallbacks[key](isDark)
}
});
// this function is used as the event listener for toggle-theme button click
function toggleThemeListener() {
// console.log('click theme-toggle')
window.dispatchEvent(new CustomEvent('toggle-theme'));
}
</script>
<script>
// load theme, as early as possible