I am building very simple github page as a CV (I am not a web developer) and I have a strange issue with behavior of website when it is loaded very first time.
I have a toggle button that switches theme dark/light. When I visit this website very first time (or after cache a cookies clearing) I can switch to light but not back to dark (original). After refresh of website everything works just fine.
I use JS to toggle theme (but code itself does not seem to be problem):
// Check the user's theme preference from local storage
const currentTheme = localStorage.getItem('theme');
if (currentTheme) {
body.classList.add(currentTheme);
updateThemeLabel(currentTheme);
}
themeToggle.addEventListener('change', () => {
if (body.classList.contains('light-mode')) {
// If the current theme is light, switch to dark
body.classList.replace('light-mode', 'dark-mode');
updateThemeLabel('dark-mode'); // Update the theme label text and color
localStorage.setItem('theme', 'dark-mode');
} else {
// If the current theme is dark, switch to light
body.classList.replace('dark-mode', 'light-mode');
updateThemeLabel('light-mode'); // Update the theme label text and color
localStorage.setItem('theme', 'light-mode');
}
});
function updateThemeLabel(theme) {
if (theme === 'dark-mode') {
themeLabel.textContent = 'Burn your eyes';
themeLabel.style.color = '#fff';
footer.style.color = '#fff';
footer.style.backgroundColor = '#333';
body.style.backgroundColor = '#333';
body.style.color = '#fff';
socialIconTwitter.style.color = '#fff';
socialIconLinkedin.style.color = '#fff';
} else {
themeLabel.textContent = 'Quickly back!';
themeLabel.style.color = '#000';
footer.style.color = '#000';
footer.style.backgroundColor = '#fff';
body.style.backgroundColor = '#fff';
body.style.color = '#000';
socialIconTwitter.style.color = '#000';
socialIconLinkedin.style.color = '#000';
}
}
Website is https://cralost.github.io/resume/
>Solution :
This is always false:
if (body.classList.contains('light-mode'))
Until the user selects something and reloads the page, at which time you set a class here:
body.classList.add(currentTheme);
But you never add that class in the change event handler. Instead, you do this:
body.classList.replace('dark-mode', 'light-mode');
But if the classList doesn’t contain 'dark-mode' then there’s nothing to replace.
Instead, remove and add the classes. For example:
themeToggle.addEventListener('change', () => {
if (body.classList.contains('light-mode')) {
body.classList.remove('light-mode'); // remove light mode
body.classList.add('dark-mode'); // add dark mode
updateThemeLabel('dark-mode');
localStorage.setItem('theme', 'dark-mode');
} else {
body.classList.remove('dark-mode'); // remove dark mode
body.classList.add('light-mode'); // add light mode
updateThemeLabel('light-mode');
localStorage.setItem('theme', 'light-mode');
}
});