From b67d5df2e08a69f850db68f1fa9075e367623508 Mon Sep 17 00:00:00 2001 From: Reorx Date: Wed, 1 Jun 2022 17:42:42 +0800 Subject: [PATCH] ensure the toggle theme click event listener is only added once --- layouts/partials/footer.html | 7 ++++--- layouts/partials/header.html | 7 +++++++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/layouts/partials/footer.html b/layouts/partials/footer.html index 750db18..e4e7d8e 100644 --- a/layouts/partials/footer.html +++ b/layouts/partials/footer.html @@ -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) })(); diff --git a/layouts/partials/header.html b/layouts/partials/header.html index 2e7512d..1061d5b 100644 --- a/layouts/partials/header.html +++ b/layouts/partials/header.html @@ -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')); +} +