javascript dark mode - Add Dark Mode using localStorage - MinoPress

Get FREE Premium WordPress Blog Theme

Download Now
MinoPress Logo
  • Home
  • Products
      • Azi Theme - $24
        Azi Theme - $24Multipurpose Woocommerce Theme
      • Muskan <br> $19
        Muskan
        $19
        Multipurpose Woocommerce Theme
      • AAnglo - FREE
        AAnglo - FREELifestyle Blog WordPress Theme
      • Jusako - $19
        Jusako - $19eCommerce HTML5 Template
      View all products
    • Muskan Theme
    • Azedw Theme
    • Aanglo Theme
    • Jusako Template
  • Services
    • WordPress theme Customization
    • WordPress theme installation
    • Custom WP plugin development
    • Convert HTML to WP Theme
    • Convert PSD to WP Theme
    • Custom website design with Figma / Sktch / Xd
    • Convert psd / Figma / Sktch / Xd to html
    • View all services
  • Pricing
  • Blog
    • eCommerce
    • JavaScript
    • Maintenance And Code
    • Review
    • Security
    • Server
    • Snippets
    • SEO And Digital Marketing
    • Speed And Performance
    • Tutorial
    • User Experience
    • WordPress
    • All Articles
  • About
  • Support
    • Documentation
    • Create Ticket
    • Contact Us

Search

No products in the cart.

javascript dark mode – Add Dark Mode using localStorage

Maintenance And Code

  • By: mino-press
  • December 16, 2021
javascript dark mode

Dark Mode (use javascript for dark mode) or Dark Theme on websites has become quite common lately. And with this trend in iOS, macOS & Windows, most systems or apps have already adopted the same dark themes.

“Dark mode” makes your site more attractive to users who prefer darker colors. The user experience will be better if you allow functionality to switch between light theme and dark theme.

In this short post, I will show how to add dark mode using javascript and localStorage, one that works the same way as the button at the bottom right of the screen in this blog.

Create the relevant CSS files

For starters create two CSS files, one light-theme.css that will be blank and the other named dark-theme.css that will contain all the CSS settings for the same javascript dark mode, i.e. for the same Dark Mode on your site.

The light-theme.css file will be empty because Light Theme is actually the standard CSS of the site. It may sound a bit redundant or less effective, but if you know or are able to create a better way to implement it we would be very happy if you share us in the comments.

Add these files to the CSS folder on your site. Then add a call to the CSS file in the site’s head as follows:

<link id="light-theme-css-link" rel="stylesheet" type="text/css" href="/your-path/light-theme.css"/>

Note that you change the path to a file depending on its location in the site folder.

javascript dark mode – Create a button to switch to dark mode

Creating a button that switches between the modes We will add the following markup to the Footer of our site:

<button id="toggle-mode-button">Change Mode</button>

Example CSS code for positioning and designing the button at the bottom right of the window

#toggle-mode-button {
    position: fixed;
    right: 12px;
    left: auto;
    bottom: 12px;
    display: inline-block;
    z-index: 1000;
    text-indent: -999999px;
    width: 40px;
    height: 40px;
    background: linear-gradient(-45deg, #ffd600, #ffd600 49%, #fefefe 49%, #fefefe 51%, #2d2d2d 51%);
    border-radius: 50%;
    border: 0;
}

The JavaScript that will switch between the modes

In order to maintain the user’s setting so that the information in which situation he is interested in viewing the site, we will use localStorage. If you do not know, localStorage is a functionality that allows you to save pairs of key/value in your browser.

The information in localStorage is stored in the browser even after the page is refreshed and even after the user reboots the browser.

You can check which values are saved for a particular site in localStorage using the browser’s Developer Tools under the Application tab. Here’s an example of what it looks like in Chrome Dev Tools:

switch between the modes

Let’s see the code we use to save this value in the browser, and then explain it a bit. This is the function:

document.addEventListener('DOMContentLoaded', () => {
    const themeStylesheet = document.getElementById('toggle-mode-button');
    const themeToggle = document.getElementById('toggle-mode-button');
    const storedTheme = localStorage.getItem('themeColor');

    if (storedTheme) {
        themeStylesheet.href = storedTheme;
    }
    themeToggle.addEventListener('click', () => {
        // if it's dark -> go light
        if (themeStylesheet.href.includes('dark')) {
            themeStylesheet.href = '/your-path/light-theme.css';
            themeToggle.innerText = 'Switch to light mode';
        } else {
            // if it's light -> go dark
            themeStylesheet.href = '/your-path/dark-theme.css';
            themeToggle.innerText = 'Switch to dark mode';
        }
        // save the preference to localStorage
        localStorage.setItem('themeColor', themeStylesheet.href)
    })
})

We run the function only after DOMContentLoaded, this is an event that indicates that all the HTML is loaded and parsed without waiting for images, CSS files and the like to load.

Before we explain the code, note that you are changing the path within the second block if to the correct path of the CSS files we created earlier.

A few words on the code up

The code is pretty simple to understand – first we target the same link to the CSS file we added in the site’s head and put it into a variable called themeStylesheet.

We then target the button we created, the one that switches between dark mode and normal mode, and put it into a variable called themeToggle.

We then check for information in the browser’s localStorage key called themeColor. If it exists, that is, if the user previously clicked the button and the preferred mode setting already exists in localStorage, then it is determined that the link to the CSS file will contain the address of that relevant CSS file, whether the dark-theme.css or light-theme.css file.

If it was not clear – the value of the same key we keep in localStorage would be the URL of the relevant CSS file, i.e. one of the same files we created earlier – light-theme.css or the dark-theme.css file.

We then listen to the event at the click of a button, if the address of the CSS file contains the word dark, we will replace the address with the clear CSS file, ie light-theme.css which has no special CSS setting. And of course, the same action is performed in the opposite case and an address contains the word light.

And finally, we make sure that if there is nothing in localStorage, you will save the address name for the light-theme.css file that does not contain any special definition.

In conclusion

In this post, we explained how to add “Dark Mode” to your site. I did not mention this in the post, but the use of CSS Variables can be excellent in this case.

  • twitter
  • facebook
  • WhatsApp
  • Google+
  • Pinterest
  • LinkedIn
  • Buffer

Previous Post

Shopify or WordPress?

Next Post

16 types of WordPress websites

0 0 votes
Article Rating
Subscribe
Login
Notify of
guest
guest
0 Comments
Inline Feedbacks
View all comments

Search


Recent post

Choosing color combinations for a website – color psychology
January 13, 2022

Choosing color combinations for a website – color psychology

The Best WordPress Plugins Guide
January 11, 2022

The Best WordPress Plugins Guide

How to choose the best WordPress hosting for Your Website
March 9, 2022

How to choose the best WordPress hosting for Your Website

WordPress 301 redirect and 302 redirect
February 10, 2022

WordPress 301 redirect and 302 redirect

What is Woocommerce?
January 26, 2022

What is Woocommerce?

Catetories

  • category image General
  • category image WordPress
  • category image Review
  • category image Tutorial
  • category image JavaScript
  • category image Security
  • category image eCommerce
  • category image Maintenance And Code
  • category image Speed And Performance
  • category image User Experience
  • category image SEO And Digital Marketing
  • category image Snippets
  • category image Server

Tags

  • promoting
  • snippet
  • hosting
  • CSS
  • CDN
  • archive
  • Content
  • UI
  • blogging
  • Shopify
  • SEO
  • UX
  • Review
  • WordPress
  • Tips
  • User Interface
  • Elementor
  • how to
  • wordpress security headers
  • User Experience
  • Gutenberg
  • image optimization
  • wordpress security
  • Domain
  • SVG
  • code example
  • Digital Marketing
  • domain name
  • javascript
  • Speed
  • 301
  • Woocommerce
  • Improving
  • 302
  • Security
  • plugin
  • redirect
  • Guide
  • Plugins
  • PHP
  • localStorage
  • colors
  • hook
  • Dark Mode
  • psychology
  • filter
  • Mistakes
  • gzip
  • action
  • optimization
  • compression
  • Glossary

Newsletter signup

Subscribe to the MinoPress newsletter to get the latest news Tutorial and guides, premium and free theme releases, updates, promotions, and more!

Please wait...

Thank you for sign up!

Logo footer logo

Our goal is to make life easy for web developers in the most optimal way, with modern and contemporary designs, (even without knowledge of code writing to succeed in creating amazing websites). Our motto is quality above all

Follow us:
  • FB
  • YU
  • LI

Contact info

  • Email: admin@minopress.com
  • Submit Ticket: Support


  • My account
  • Documentation
  • MinoPress FAQ

© 2021 WP Studio , All Rights Reserved

payment methods
  • Contact Us
  • Support
  • Terms and Conditions
  • Refund and Returns Policy

This website uses cookies to improve your experience. By using this website you agree to our Data Protection Policy.

Read more

PREMIUM WORDPRESS THEMES & SERVICES Dismiss

wpDiscuz