Search code examples
javascripthtmldarkmode

Toggle icon not showing unless I click it


I am using a dark mode code. With this code, I want to toggle between dark mode and light mode using respective icons. This works perfectly, but the only issue is dark/light icon is not shown by default when page loads. If I click the icon, then only it shows. How can I make it show by default when page loads.

Here's the code I'm using:

  const switcher = document.querySelector("#switcher");
    switcher.setAttribute('src', '...LIGHT-MODE-1.png');

    const toggleSwitch = document.querySelector('.theme-switch input[type="checkbox"]');
    const currentTheme = localStorage.getItem('theme');
    if (currentTheme) {
        document.documentElement.setAttribute('data-theme', currentTheme);
        if (currentTheme === 'dark') {
            toggleSwitch.checked = true;
        }
    }

    function switchTheme(e) {
        if (e.target.checked) {
            document.documentElement.setAttribute('data-theme', 'dark');
            localStorage.setItem('theme', 'dark');
            switcher.setAttribute('src', '...LIGHT-MODE-1.png');
        } else {
            document.documentElement.setAttribute('data-theme', 'light');
            localStorage.setItem('theme', 'light');
            switcher.setAttribute('src', '...DARK-MODE-1.png');
        }
    }
    toggleSwitch.addEventListener('change', switchTheme, false);
<!--The icon HTML-->


<label class="theme-switch" for="checkbox">
        <span title="Enable/disable Dark Mode"><img id="switcher" src=""></span>
        <input type="checkbox" id="checkbox" /></label>

Thanks for your help and time!


Solution

  • It seems you're missing the src change in the first dark mode check:

    if (currentTheme === 'dark') {
        toggleSwitch.checked = true;
        switcher.setAttribute('src', '...DARK-MODE-1.png');
    }
    

    Update: Instead of all the duplicate code, I would recommend creating one function that sets the theme, which you can then call from anywhere. This will allow you to use it at initial load, and on click:

    const switcher = document.querySelector('#switcher');
    const toggleSwitch = document.querySelector('.theme-switch input[type="checkbox"]');
    
    function setTheme(theme) {
        document.documentElement.setAttribute('data-theme', theme);
        localStorage.setItem('theme', theme);
    
        const src = '/path/to/images/' + (theme === 'light' ? 'LIGHT-MODE-1.png' : 'DARK-MODE-1.png');
        switcher.setAttribute('src', src);
    }
    
    const theme = localStorage.getItem('theme') || 'light';
    setTheme(theme);
    
    toggleSwitch.addEventListener('change', (e) => {
        const theme = e.currentTarget.checked ? 'dark' : 'light';
        setTheme(theme);
    });
    

    Fiddle: https://jsfiddle.net/fjzue6wa/1/