How to Make The Website'S Dark Mode Persistent With Local Storage, Css and Js

by Tibor Kopca Date: 22-12-2020 javascript webdev css code programming


Recently we wrote about how to do a switchable alternative color mode or theme, a very useful and popular feature to websites. Today’s article is going to be about how to store a user’s settings on your website, specifically, how to save dark mode settings and restore it when a user comes back to your page.

This would be a small update to our previous article about how to make a dark mode theme on your website.

Since web browsers and servers use HTTP protocol which is stateless, something was necessary for the website to “remember” stateful information such as logging in, buttons clicked by user, site preferences, items added into shopping cart, previously entered form fields, etc.

And that something we are going to learn to use.

Why do we need the persistence?

Well the default functionality of browsers is to show the data that comes from a server and it doesn’t store anything - it's stateless. If we have a multi page website or some functionality implemented on our page which will make the page refresh, or simply user hits F5, the page will be set to the default state. That means the JavaScript code for the switch of the color will be set back to default and all changes or configurations made by the user will be lost - the page will look again as freshly loaded - in our case the default color is day theme.

A web developer can implement functionality to remember some data, such as our buttons or previously filled form field, or text size changes for example if needed. And that’s why the local storage or other methods of storing the data are used. With them we can store locally the setting of our button in the browser of the client (on the user’s computer), so every time the user visits or accesses our website he/she would have the button for dark mode in the state it was the last time. The data we want there basically “persist” even when the browser is closed and reopened.

And the knowledge of how to store and keep some configuration of the website on the client's browser is very useful also in other projects, so let's go into it.

Using Local Storage

With Web Storage API mechanisms like localStorage or sessionStorage we can store key/value pairs, in a much more intuitive fashion than using cookies.
 

LocalStorage is similar to sessionStorage, except that while data stored in localStorage has no expiration time, and data stored doesn't get cleared when the page session ends — that is, when the page is closed the sessionStorage data will be cleared in sessionStorage, but localStorage data persists even when the browser is closed and reopened.

So localStorage stores data with no expiration date, and gets cleared only through JavaScript, or clearing the Browser cache / Locally Stored Data, storage limit is the maximum from the three systems - 10MB. For example cookies have only 4kB and sessionStorage 5MB.

Let’s code it!

Last time we showed that with this part of the JS code we manipulate the classes of HTML elements and by that we can set which CSS selectors are being used currently. In short, when the user clicks on the button, the code will toggle between the body has OR has not the class dark and the button class active.

const switchButton = document.getElementById('switch');
 
switchButton.addEventListener('click', () => {
document.body.classList.toggle('dark'); //toggle the HTML body the class 'dark'
switchButton.classList.toggle('active');
//toggle the HTML button with the id='switch' with the class 'active'
});

Now it's time to code the local storage part.


What we need is to check if the ‘dark’ mode is selected, and if not we store the value specifically saying that he has light mode, because if we only store the dark mode value, next time user select the light mode it wouldn't be stored the change and only dark mode would be always be on forever.
This is code for it. We check first if the body has the class ‘dark’ active and then we set the localStorage with method .setItem with two information in it, the key and value - key would be ‘darkMode’ so we know when looking at the information what it represents, and the value would be ‘enabled’ for example.

const switchButton = document.getElementById('switch');
const workContainer = document.getElementById('work');
 
switchButton.addEventListener('click', () => {
    document.body.classList.toggle('dark'); //toggle the HTML body the class 'dark'
    switchButton.classList.toggle('active');//toggle the HTML button with the id='switch' with the class 'active''
    workContainer.classList.toggle('dark');
 
   if(document.body.classList.contains('dark')){ //when the body has the class 'dark' currently
        localStorage.setItem('darkMode', 'enabled'); //store this data if dark mode is on
    }else{
        localStorage.setItem('darkMode', 'disabled'); //store this data if dark mode is off
    }
});

And when we check the website in the browser inspector(after refreshing the page), in the storage tab we can see the information being saved, just like we wanted.

Persistent_Dark_Mode_localstorage_browser_inspector_dark_mode_enabled
How do we know if the user has come to our site again with the information what type of theme he has selected last time? We need to check for this information, with the use of .getItem method of localStorage, like this:

const switchButton = document.getElementById('switch');
const workContainer = document.getElementById('work');
 
switchButton.addEventListener('click', () => {
    document.body.classList.toggle('dark'); //toggle the HTML body the class 'dark'
    switchButton.classList.toggle('active');//toggle the HTML button with the id='switch' with the class 'active''
    workContainer.classList.toggle('dark');
 
    if(document.body.classList.contains('dark')){ //when the body has the class 'dark' currently
        localStorage.setItem('darkMode', 'enabled'); //store this data if dark mode is on
    }else{
        localStorage.setItem('darkMode', 'disabled'); //store this data if dark mode is off
    }
});
 
if(localStorage.getItem('darkMode') == 'enabled'){
    document.body.classList.toggle('dark');
    switchButton.classList.toggle('active');
    workContainer.classList.toggle('dark');
}

Notice that when we check if the ‘darkMode’ has the value ‘enabled’ , this value is not boolean, but of type string, so it needs to be in commas. The check if the dark mode is disabled is not needed, because the page will be loaded by default without the dark mode class.
Another detail is we need to set accordingly the position of the button, for it to represent the correct state, without this we would have a mess with the page in dark mode and the button showing us the light mode is on.


Now it is possible to refresh the page (F5) and not lose the settings we have set on the website. And this is very useful even with other types of settings of the interactive elements. For instance when you need to save something for longer periods of time, like basket information of the e-shop or for storing UI state.


Just a note : If you're interested in syntax which will remove localStorage information we added, it should be like this:

localStorage.removeItem('darkMode');
localStorage.clear(); //The syntax for removing all the localStorage items

Conclusion

This example showed you how we can use Web Storage - specifically Local Storage - to keep information in a user's browser for longer periods of time and exploit this technique to store settings of the visual appearance of our website.
The data or settings will not be deleted when the browser is closed, and will be available anytime the user visits the page again, which allows us to employ interactivity to our site.

We explained how to create JavaScript code to show the state of the website as it was set last time across sessions and device or browser shutdowns, and this client side persistence can be used in a variety of situations.

 
by Tibor Kopca Date: 22-12-2020 javascript webdev css code programming hits : 536  
 
 
 
 

Related Posts

Validating HTML forms using BULMA and vanilla JavaScript

Today we are going to write about contact forms and how to validate them using JavaScript. The contact form seems to be one of the top features of every basic home…

A FULFILLED PROMISE - Using the FETCH API to make AJAX calls

In this article we talked about what AJAX calls are and how to use them in a traditional way, by using the XMLHttpRequest (XHR) object. In short, thanks to AJAX…

How to use Parallax.js effect on your website

Today, we're going to write about the parallax effect, similar to parallax scrolling, and how to implement it to improve your landing page. In webdev, they say mobile first -…

The easiest way to align items using flexbox

With the release of flexbox in CSS, it has become an essential tool when placing elements next to each other, since, by default, the children of a display: flexare stacked…

Dark Mode on website using CSS and JavaScript

In today’s article we are going to learn how to build pretty much standard these days on the web pages and that is the alternative color mode and switching between…

A Java Approach: Selection Structures - Use Cases

Hello everyone and welcome back! Up to now we have been concerned to make as complete an overview as possible of the fundamental concepts we need to approach the use…

JavaScript: Spread and Rest operators

In today’s article we are going to talk about one of the features of the ES6 version(ECMAScript 2015) of JavaScript which is Spread operator as well as Rest operator. These features…

How To Add Filter Effects to Images with CSS

To achieve interesting effects on your images, learn about the 'filter' and 'Backdrop-Filter' properties of CSS. CSS filters are a very attractive feature of CSS that allows you to apply certain…

Why You Should Hire Node.js Developer for Your Backend Development

When developers are building a new website, they mainly focus on both frontend and backend development. The frontend code helps create the interfaces through which the app interacts with the…

Hashmap: Overflow Lists

In this short series of articles we will go to see how it is possible to create the Hashmap data structure in C. In the implementation we're going to use the…

Javascript: what are callbacks and how to use them.

Today we are going to learn about a concept that is widely used in javascript and that is used quite a lot by today's frameworks, libraries, especially NodeJS. This is…

Data structures in Java - Linked Lists

With 2020 we are going to look at a new aspect of programming: data structures. It is often the case that everyone uses structures provided by the various programming languages.…