Light & Dark Mode jQuery Toggle Using localStorage

Light & Dark Mode jQuery Toggle Using localStorage

So, you are searching to accomplish light and dark mode jQuery toggle on your website. Yes, that is the tutorial for you. 

In this tutorial, I’m going to illustrate to you how to implement a jQuery toggle to switch the light and dark mode of your website and I shall use localStorage API to save switch mode in the browser. As a result, if a visitor refreshes the page or goes to another page it won’t change until another click on the toggle button.

I believe visitors will love this feature and really it is very convenient to read content/articles for a long time.

Now, let’s start –

First and foremost, going to declare the toggle class name as “mode-switcher” inside HTML div. You may use it anywhere on your website actually where you would like to show your toggle ( light and dark ) icon. Especially header is the best place what everyone doing this and it is UI and UX friendly. You can also put it on the sidebar. Eventually, I would like to say it should be visual for visitors.

<div class="mode-switcher">
    <i class="las mode-icon-change"></i>
</div>

Now, going to write jQuery code inside $(document).ready(function(){});

Step 2: First, check localStorage value that is saved or not and store it into a variable. I’ve declared a variable name as “switchMode”.

// Check for saved 'switchMode' in localStorage
let switchMode = localStorage.getItem('switchMode');

Step 3: Bind the selector class, which I’ve declared in the first snippet, and assign it to a variable name as “switchModeToggle”.

      // Get selector
      const switchModeToggle = $(' .mode-switcher ');

Step 4: Write a function for dark mode and assign this function to a variable whose name is “enableDarkMode”. When this function will trigger, it’ll add a class in the body tag. I’ve taken this class name “likhun-dark”. Besides, it’ll update the localStorage value as “enabled” for which the key is “switchMode”. 

      // Dark mode function
      const enableDarkMode = function() {
          // Add the class to the body
          $( 'body' ).addClass('likhun-dark');
          // Update switchMode in localStorage
          localStorage.setItem('switchMode', 'enabled');
      }

Step 5: In this step, I’m going to write another function to disable dark mode, which means enable light mode. Triggering this function will remove “likhun-dark” class from the body tag and it’ll update the localStorage value as “NULL”.

      // Light mdoe function
      const disableDarkMode = function() {
          // Remove the class from the body
          $( 'body' ).removeClass('likhun-dark');
          // Update switchMode in localStorage value
          localStorage.setItem('switchMode', null);
      }

Step 6: Here, I’ll keep mode enabled or disabled throughout the website. At first, check the switchMode value from localStorage; if it is “enabled”, show dark else light mode. That’s why I’m calling “enableDarkMode()” function when the localStorage “switchMode” value is enabled else value is NULL. Another interesting thing is added- change the trigger icon, when in dark mode, it’ll add the “la-moon” class for the night icon and remove the “la-sun” class for the light icon. The same work is also done in the light mode. 

Note: I’ve used Line Awesome icon class.

        // If the user already visited and enabled switchMode
        if (switchMode === 'enabled') {
            enableDarkMode();
            // Dark icon enabled
            $( '.mode-icon-change' ).addClass( 'la-moon' );
            $( '.mode-icon-change' ).removeClass( 'la-sun' );
        } else {
            // Light icon enabled
            $( '.mode-icon-change' ).addClass( 'la-sun' );
            $( '.mode-icon-change' ).removeClass( 'la-moon' );
        }

Step 7: In the final step, write a click event to change mode. When the event will happen, it’ll change the icon and verify the latest localStorage switchMode value. If localStorage value is “enabled”, dark mode will be active instantly; on the other hand, if localStorage value is “NULL” light mode will activate.

// When someone clicks the button
switchModeToggle.on('click', function() {
    // Change switch icon
    $( '.mode-icon-change' ).toggleClass( 'la-sun' );
    $( '.mode-icon-change' ).toggleClass( 'la-moon' );

    // get their switchMode setting
    switchMode = localStorage.getItem('switchMode');
   
    // if it not current enabled, enable it
    if (switchMode !== 'enabled') {
	enableDarkMode();              
    // if it has been enabled, turn it off  
    } else {  
	disableDarkMode();              
    }
});

Now you can write CSS code for your dark mode for instance –

body.likhun-dark {
    background: #191919;
    color: #ffffff;
}
.likhun-dark header.page-header.likhun-page-header {
    background: #333333;
    color: #ffffff;
}

Finally, I’m giving the complete HTML and jQuery code below –

HTML code:

<div class="mode-switcher">
    <i class="las mode-icon-change"></i>
</div>

jQuery code:

$(document).ready(function(){    

    /**
    * Light & Dark Mode jQuery Toggle Using localStorage
    */    

    // Check for saved 'switchMode' in localStorage
    let switchMode = localStorage.getItem('switchMode');

    // Get selector
    const switchModeToggle = $(' .mode-switcher ');

    // Dark mode function
    const enableDarkMode = function() {
        // Add the class to the body
        $( 'body' ).addClass('likhun-dark');
        // Update switchMode in localStorage
        localStorage.setItem('switchMode', 'enabled');
    }

    // Light mdoe function
    const disableDarkMode = function() {
        // Remove the class from the body
        $( 'body' ).removeClass('likhun-dark');
        // Update switchMode in localStorage value
        localStorage.setItem('switchMode', null);
    }

    // If the user already visited and enabled switchMode
    if (switchMode === 'enabled') {
        enableDarkMode();
        // Dark icon enabled
        $( '.mode-icon-change' ).addClass( 'la-moon' );
        $( '.mode-icon-change' ).removeClass( 'la-sun' );
    } else {
        // Light icon enabled
        $( '.mode-icon-change' ).addClass( 'la-sun' );
        $( '.mode-icon-change' ).removeClass( 'la-moon' );
    }

    // When someone clicks the button
    switchModeToggle.on('click', function() {
        // Change switch icon
        $( '.mode-icon-change' ).toggleClass( 'la-sun' );
        $( '.mode-icon-change' ).toggleClass( 'la-moon' );

        // get their switchMode setting
        switchMode = localStorage.getItem('switchMode');

        // if it not current enabled, enable it
        if (switchMode !== 'enabled') {
            enableDarkMode();              
        // if it has been enabled, turn it off  
        } else {  
            disableDarkMode();              
        }
    });

}); // End load document

Promotional:

If you are searching for web templates or themes for your business or freelance work, you may check our vast collections. I believe you’ll get your desired web template or theme for your startup.

Post a Comment