Introduction
dark mode is starting to become a trending/mandatory feature in the modern web, and a lot of folks asked me about how to make it works.
Today in this article, I'll explain how to switch between the dark, light and the default browser mode, with a simple way.
Requisites
- The basics of JavaScript
- Familiarity with Tailwindcss
If you don't have any experience using tailwindcss, that's perfectly fine, I'll try to explain it along the way.
Note: If you are already knows how to deal with tailwindcss, please head directly into preparing for switching section.
What's Tailwindcss
According to the website tagline
A utility-first CSS framework packed with classes like flex, pt-4, text-center and rotate-90 that can be composed to build any design, directly in your markup.
In other meaning, tailwindcss is a CSS framework to help you write your styles directly into your HTML files, instead of writing a custom class to a button
for example, you can do it directly
1<button class="rounded py-4 px-2 bg-indigo-600 hover:bg-indigo-900">Submit</button>
Each class represents a set of css
properties/values.
Color Scheme
According to MDN
The
color-scheme
CSS property allows an element to indicate which color schemes it can comfortably be rendered in.
The Color Scheme is a way to define the preferred color scheme by the user.
JavaScript LocalStorage
According to MDN
The localStorage read-only property of the window interface allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions.
The LocalStorage, is like a session
function (If you are a backend developer), and it helps you store a set of keys/values inside the browser localStorage, to easily retrieve it, and to remember the user choice.
Initialize Tailwindcss Project
The Tailwind Docs, is really straight forward, and the folks who's behind it, doing a really great job, explain each piece in a really nice way, and for the sake of this article, I'll briefly mention what we need to know.
Install Tailwindcss
1npm install -D tailwindcss2npx tailwindcss init
Configure your template paths
After Installing tailwindcss and initialize the tailwind.config.js
file, you need to configure the template path (content
) to tell tailwind where to look.
1/** @type {import('tailwindcss').Config} */2module.exports = {3 content: ["./src/**/*.{html,js}"],4 theme: {5 extend: {},6 },7 plugins: [],8}
Add Tailwind directives to your CSS
1@tailwind base;2@tailwind components;3@tailwind utilities;
Start the tailwind CLI build process
1npx tailwindcss -i ./src/input.css -o ./dist/output.css --watch
After that, include the compiled CSS output.css
and include it into your HTML file, then enjoy!
Preparing For Switching
This is the excited part in the article, first you need to create a file called compnents/theme.js
or whatever name you want to easily require it after, and past the following code
1export const toDarkMode = () => { 2 localStorage.theme = 'dark'; 3 window.updateTheme(); 4} 5 6export const toLightMode = () => { 7 localStorage.theme = 'light'; 8 window.updateTheme(); 9}10 11export const toSystemMode = () => {12 localStorage.theme = 'system';13 window.updateTheme();14}
Simply here, we are creating a function for each color scheme
, and we are storing the value under theme
key in the localStorage
, and we call the updateTheme
function, which we'll create later in this article.
After you create the theme.js
file inside the components
directory, you need to import it in your main JavaScript file
1import {toDarkMode, toLightMode, toSystemMode} from './components/theme';2 3window.toDarkMode = toDarkMode;4window.toLightMode = toLightMode;5window.toSystemMode = toSystemMode;
After we declared the main theme
file, we make the functions global accessible, to use them later.
Update Theme Function
After we have done all the above, now it's time to create the updateTheme
function (name of however you want :smile:)
First, we check if the theme
key exists inside the localStorage
or not, if not. We'll create one and assigned the default color-scheme
to the default (system
)
1function updateTheme() {2 if (! ('theme', in localStorage) ) {3 localStorage.theme = 'system';4 }5}
After that, we make a switch statement, to determine the value of the theme
inside the localStorage
1switch(localStorage.theme) { 2 case 'system': 3 if (window.matchMedia('(prefers-color-scheme: dark').matches) { 4 document.documentElement.classList.add('dark'); 5 } else { 6 document.documentElement.classList.remove('dark'); 7 } 8 document.documentElement.setAttribute('color-theme', 'system'); 9 break;10 case 'dark':11 document.documentElement.classList.add('dark');12 document.documentElement.setAttribute('color-theme', 'dark');13 break;14 case 'light':15 document.documentElement.classList.remove('dark');16 document.documentElement.setAttribute('color-theme', 'light');17 break;18}
Simply here, we act depends on the theme
value, and for the system
value, we make another check, if the prefers-color-scheme is dark
by default, or light
What this function does, is check for the mode, and adds/remove the dark
class, and the color-theme
attribute.
Switch Theme Buttons
As you can see, we use in Coderflex The theme switch feature, and this is what we use behind the scenes
1<div class="ml-4"> 2 <button id="header__sun" onclick="toSystemMode()" title="Switch to system theme" class="relative w-10 h-10 focus:outline-none focus:shadow-outline text-gray-500"> 3 <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-sun" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> 4 <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> 5 <circle cx="12" cy="12" r="4"></circle> 6 <path d="M3 12h1m8 -9v1m8 8h1m-9 8v1m-6.4 -15.4l.7 .7m12.1 -.7l-.7 .7m0 11.4l.7 .7m-12.1 -.7l-.7 .7"></path> 7 </svg> 8 </button> 9 <button id="header__moon" onclick="toLightMode()" title="Switch to light mode" class="relative w-10 h-10 focus:outline-none focus:shadow-outline text-gray-500">10 <svg style="width:24px;height:24px" viewBox="0 0 24 24">11 <path fill="currentColor" d="M17.75,4.09L15.22,6.03L16.13,9.09L13.5,7.28L10.87,9.09L11.78,6.03L9.25,4.09L12.44,4L13.5,1L14.56,4L17.75,4.09M21.25,11L19.61,12.25L20.2,14.23L18.5,13.06L16.8,14.23L17.39,12.25L15.75,11L17.81,10.95L18.5,9L19.19,10.95L21.25,11M18.97,15.95C19.8,15.87 20.69,17.05 20.16,17.8C19.84,18.25 19.5,18.67 19.08,19.07C15.17,23 8.84,23 4.94,19.07C1.03,15.17 1.03,8.83 4.94,4.93C5.34,4.53 5.76,4.17 6.21,3.85C6.96,3.32 8.14,4.21 8.06,5.04C7.79,7.9 8.75,10.87 10.95,13.06C13.14,15.26 16.1,16.22 18.97,15.95M17.33,17.97C14.5,17.81 11.7,16.64 9.53,14.5C7.36,12.31 6.2,9.5 6.04,6.68C3.23,9.82 3.34,14.64 6.35,17.66C9.37,20.67 14.19,20.78 17.33,17.97Z" />12 </svg>13 </button>14 <button id="header__indeterminate" onclick="toDarkMode()" title="Switch to dark mode" class="relative w-10 h-10 focus:outline-none focus:shadow-outline text-gray-500">15 <svg style="width:24px;height:24px" viewBox="0 0 24 24">16 <path fill="currentColor" d="M12 2A10 10 0 0 0 2 12A10 10 0 0 0 12 22A10 10 0 0 0 22 12A10 10 0 0 0 12 2M12 4A8 8 0 0 1 20 12A8 8 0 0 1 12 20V4Z" />17 </svg>18 </button>19</div>
The onclick
attribute call the defined functions in theme.js
file, and it switches the color-scheme
.
If you want to show/hide the desired icon, depends on the color-scheme
, use this style
1#header__sun, #header__moon, #header__indeterminate { 2 display: none; 3} 4 5html[color-theme="dark"] #header__moon { 6 display: block; 7} 8html[color-theme="light"] #header__sun { 9 display: block;10}11html[color-theme="system"] #header__indeterminate {12 display: block;13}
Switching the layout
Tailwind has a simple way to switch between the dark
and the light
mode
First, you need to define the class dark
into your html
tag (which we don't have to)
Then, If you want a dark style, prefix the class with dark:
. If it's light, don't.
1<!-- Light Mode Style-->2<button class="bg-indigo-600 hover:bg-indigo-900">Submit</button>3 4<!-- For Dark Mode -->5<button class="dark:bg-red-600 dark:hover:bg-red-900">Submit</button>
For more info, please take a look at the official documentation section for the dark mode.
Conclusion
Hope this article has helped a little on your journey, for making the dark mode toggle with tailwindcss, and if you are into this kind of articles, or in programming in general, take a look at my Twitter profile