How to switch Light and Dark mode on Web

Dark mode

Dark mode has gained a lot of attraction recently. Different Operating systems like Mac and Windows have adopted the dark and light mode for their UI. Similarly for mobile, different apps have been adopting the dark and light mode. For websites too, YouTube, Facebook and all other sites have these features. So as a frontend developer we should learn to develop this feature. Today I am going to design a Social Dashboard which will include a toggle switch for dark and light mode and we will have the mode change according to the system settings too. So, let’s get started.

Dark and Light mode

You can find the source code for this project at https://gitlab.com/aneeslml/dark-mode So i wont be describing all the html and CSS aspects here, we will deal with just the mode changing functionality in this blog. For full reference please visit the source code.

Variables

At first let’s take the background color and text colors as variables. There are two colors for background, so let’s take primary-bg and secondary-bg for those. And two text colors so take them as primary-text and secondary-text. We will need color for hover too so let’s take it as hover variable.

We will take all the other social icon colors and basic colors as variables too which wont be needed to be changed according to mode.

Light mode

Now, we will first write the html and css for light theme at the beginning with light color variables. And design the UI as following:

Toggle Switch

Here for toggle switch we’ll write code as:

Here, we assigned an id for the input type checkbox as “theme-toggler”. So using this id in javascript, we can toggle between the mode in our custom.js file as:

Here, if the theme-toggler checkbox is checked then we will add an “active” class in our body tag, and if its unchecked then we will remove that “active” class. Therefore after adding an “active” class in body we will set new variables in css, that will change the color of background and text that we declared previously for light theme.

Dark mode

Thus after the addition of active class, the variables will change and the classes that were using those variables would adopt new variables that makes the webpage dark theme.

Dark mode

Operating System Settings

Now, to make our webpage change mode according to the system settings theme, we can use a media query named as “prefers-color-scheme” were we can assign the variables for that color-scheme as:

prefers-color-scheme

Thus, changing the variables according to mode using html, css and javascript we can create dark and light theme webpage.

Hope you got the idea, you can check out the source code if any confusions or do comment below for any queries.

Share on facebook
Share on twitter
Share on linkedin

Leave A Comment

Related Posts

Featured Posts
Author

Anish Lamsal

Frontend Developer

Computer Engineer pursuing his passion in blogging.