1

I'm trying to make dark light mode with javascript and local storage but something is not right. Here is the code for toggle icon

<i class="fa-regular fa-moon change-theme" title="Theme" id="theme-button"></i>

and here is js code

const themeButton = document.getElementById('theme-button')
const darkTheme = 'dark-theme'
const iconTheme = 'fa-sun'


const selectedTheme = localStorage.getItem('selected-theme')
const selectedIcon = localStorage.getItem('selected-icon')


const getCurrentTheme = () => document.body.classList.contains(darkTheme) ? 'dark' : 'light'
const getCurrentIcon = () => themeButton.classList.contains(iconTheme) ? 'fa-moon' : 'fa-sun'


if (selectedTheme) {
  document.body.classList[selectedTheme === 'dark' ? 'add' : 'remove'](darkTheme)
  themeButton.classList[selectedIcon === 'fa-moon' ? 'add' : 'remove'](iconTheme)
}


themeButton.addEventListener('click', () => {
    document.body.classList.toggle(darkTheme)
    themeButton.classList.toggle(iconTheme)
    localStorage.setItem('selected-theme', getCurrentTheme())
    localStorage.setItem('selected-icon', getCurrentIcon())
})

When I click icon it adds fa-sun to class attribute and removes it when I click again, but class fa-moon is never removed from class attribute and sun icon is not shown.

masterdeki
  • 49
  • 6

1 Answers1

0

Here is how I fixed it...first I changed icon in html code to this

<i class="fa-regular fa-sun change-theme" title="Theme" id="theme-button"></i>

and then changed js like this

const themeButton = document.getElementById('theme-button');
const darkTheme = 'dark-theme';
const darkIcon = 'fa-sun';
const lightIcon = 'fa-moon';

const selectedTheme = localStorage.getItem('selected-theme')
const selectedIcon = localStorage.getItem('selected-icon')

const getCurrentTheme = () => document.body.classList.contains(darkTheme) ? 'dark' : 'light';
const getCurrentIcon = () => themeButton.classList.contains(lightIcon) ? lightIcon : darkIcon;

document.body.classList.add(darkTheme);
themeButton.classList.add(selectedTheme === 'dark' ? lightIcon : darkIcon);

themeButton.addEventListener('click', () => {

  document.body.classList.toggle(darkTheme);
  themeButton.classList.toggle(darkIcon);
  themeButton.classList.toggle(lightIcon);

  localStorage.setItem('selected-theme', getCurrentTheme());
  localStorage.setItem('selected-icon', getCurrentIcon());
});

and now it's working like I wanted-when dark mode is on there is a sun icon and when clicked on sun lite mode is on and moon icon showed.

masterdeki
  • 49
  • 6
  • I wouldn't store both `selected-theme` and `selected-icon` in `localStorage`. Just theme is enough. You can figure out the icon based on the selected theme. – Dimitris Maragkos Sep 25 '22 at 09:09