Home Web Front-end CSS Tutorial Change Light and Dark theme in just lines of JavaScript

Change Light and Dark theme in just lines of JavaScript

Aug 21, 2024 pm 09:05 PM

Okay.. There is a little bit of CSS involved?, but it was much easier then the answers I found on the internet.

What I am Trying To Achieve?
I am trying to achieve two things with this method.

  1. I need to allow the website to load the way user-prefers it (The part where they already chose their theme in the OS)
  2. But I also want to allow them to toggle between dark and light mode after the loading.

So we will have a website that will load in the user expected theme and then allow them to change it when they want to.

Step 1: Create Button for toggling

<img class="mode" src="./img/moon.svg">
Copy after login

I am using an image as my button that has a svg image of a moon. You can add your button or checkbox that feels okay for you to toggle between two options.

Step 2: Put your color details in CSS as custom properties

:root{
    color-scheme: light dark;

    --light-bg: ghostwhite;
    --light-color: darkslategray;
    --light-code: tomato;

    --dark-bg: darkslategray;
    --dark-color: ghostwhite;
    --dark-code: gold;
}

.light{
    color-scheme: light;
}

.dark{
    color-scheme: dark;
}

Copy after login

Okay.. So in the root you are seeing property called color-scheme and this going to be our game changer.
As you can see, it takes values light or dark to it. I have also created two classes that .light and .dark that sets the value of color-scheme to dark or light.

Step 3: Add colors to various parts of your code

body{
    background-color: light-dark(var(--light-bg), var(--dark-bg));
}
Copy after login

Now whenever a property asks for a color(like background, color properties), you can use the function called light-dark().
This function takes two values, the first one is used when color-scheme is set to light and the second one is used when color-scheme is set to dark.

Yes... This is a function that is released in May 2024. It is fairly new, but It will be adapted soon. And it is in baseline support as of writing this article. Here is the docs for it

Change Light and Dark theme in just lines of JavaScript

light-dark() - CSS: Cascading Style Sheets | MDN

The light-dark() CSS function enables setting two colors for a property - returning one of the two colors options by detecting if the developer has set a light or dark color scheme or the user has requested light or dark color theme - without needing to encase the theme colors within a prefers-color-scheme media feature query. Users are able to indicate their color-scheme preference through their operating system settings (e.g. light or dark mode) or their user agent settings. The light-dark() function enables providing two color values where any value is accepted. The light-dark() CSS color function returns the first value if the user's preference is set to light or if no preference is set and the second value if the user's preference is set to dark.

Change Light and Dark theme in just lines of JavaScript developer.mozilla.org

If you use this, the CSS will automatically detect the user preference from the OS and sets it to the color they want.
We achieved our first goal, the website will load with color mode user already wanted in their OS.

Step 4: Use Javascript to toggle between dark and light mode

// mode is the toggle button 
mode.addEventListener("click", ()=>{
    // we are getting the color scheme here
    let theme = document.documentElement.style.colorScheme;
    /*  when a website is first loaded
    it will have null as its color-scheme value*/
    if(theme == null){
        // this window.matchMedia() checks if the user prefers the dark theme
        if(window.matchMedia("(prefers-color-scheme:dark)").matches){
            /* if they prefer dark, clicking on our button should turn everything to light, 
            the color-scheme will be given a value as light  */
            document.documentElement.style.colorScheme = "light"; 
        }
        // Or else the color-scheme will be set to dark
        document.documentElement.style.colorScheme = "dark";
    }

    /* Now since our toggle button set the color scheme,
        we can simply change light to dark and dark to light using below code 
    */

    else{
        document.documentElement.style.colorScheme = (theme == "light")? "dark": "light";
    }
});
Copy after login

Here, document.documentElement.style.colorScheme actually refers to the :root element from CSS.
As we already achieved to open the website in user preferred mode in the previous step,here when the toggle button is clicked it does the following jobs.

  1. It checks whether color-scheme has any value, if not, the website is in user preferred mode, we need to identify if its dark or light to change mode.
  2. It uses window.matchMedia("(prefers-color-scheme:dark)").matches to find if it is in dark mode, if it is in dark mode, we change color-scheme to light, if its not, we change it to dark.
  3. The next time they click the button, we already set value for our color-scheme, so we just toggle between dark or light.

*PS: * This is my first post and I am still a beginner to web developing. But when I searched for this method, I have not seen any related posts about it. If you already know this, I am sorry for click baiting you?. I thought this post will help me to remember this process every time I am working on a new project.
If you are working for your website to work on old browsers, this method is definitely not for you. Tell me in the comments about this post. Thanks for reading.

The above is the detailed content of Change Light and Dark theme in just lines of JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1267
29
C# Tutorial
1239
24
Google Fonts   Variable Fonts Google Fonts Variable Fonts Apr 09, 2025 am 10:42 AM

I see Google Fonts rolled out a new design (Tweet). Compared to the last big redesign, this feels much more iterative. I can barely tell the difference

How to Create an Animated Countdown Timer With HTML, CSS and JavaScript How to Create an Animated Countdown Timer With HTML, CSS and JavaScript Apr 11, 2025 am 11:29 AM

Have you ever needed a countdown timer on a project? For something like that, it might be natural to reach for a plugin, but it’s actually a lot more

HTML Data Attributes Guide HTML Data Attributes Guide Apr 11, 2025 am 11:50 AM

Everything you ever wanted to know about data attributes in HTML, CSS, and JavaScript.

A Proof of Concept for Making Sass Faster A Proof of Concept for Making Sass Faster Apr 16, 2025 am 10:38 AM

At the start of a new project, Sass compilation happens in the blink of an eye. This feels great, especially when it’s paired with Browsersync, which reloads

How We Created a Static Site That Generates Tartan Patterns in SVG How We Created a Static Site That Generates Tartan Patterns in SVG Apr 09, 2025 am 11:29 AM

Tartan is a patterned cloth that’s typically associated with Scotland, particularly their fashionable kilts. On tartanify.com, we gathered over 5,000 tartan

How to Build Vue Components in a WordPress Theme How to Build Vue Components in a WordPress Theme Apr 11, 2025 am 11:03 AM

The inline-template directive allows us to build rich Vue components as a progressive enhancement over existing WordPress markup.

While You Weren't Looking, CSS Gradients Got Better While You Weren't Looking, CSS Gradients Got Better Apr 11, 2025 am 09:16 AM

One thing that caught my eye on the list of features for Lea Verou&#039;s conic-gradient() polyfill was the last item:

A Comparison of Static Form Providers A Comparison of Static Form Providers Apr 16, 2025 am 11:20 AM

Let’s attempt to coin a term here: "Static Form Provider." You bring your HTML

See all articles