search
HomeWeb Front-endCSS TutorialChange Light and Dark theme in just lines of JavaScript

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 lazy" src="/static/imghwm/default1.png" data-src="./img/moon.svg" alt="Change Light and Dark theme in just lines of JavaScript" >

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;
}

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));
}

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";
    }
});

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
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
Demystifying Screen Readers: Accessible Forms & Best PracticesDemystifying Screen Readers: Accessible Forms & Best PracticesMar 08, 2025 am 09:45 AM

This is the 3rd post in a small series we did on form accessibility. If you missed the second post, check out "Managing User Focus with :focus-visible". In

Adding Box Shadows to WordPress Blocks and ElementsAdding Box Shadows to WordPress Blocks and ElementsMar 09, 2025 pm 12:53 PM

The CSS box-shadow and outline properties gained theme.json support in WordPress 6.1. Let's look at a few examples of how it works in real themes, and what options we have to apply these styles to WordPress blocks and elements.

Working With GraphQL CachingWorking With GraphQL CachingMar 19, 2025 am 09:36 AM

If you’ve recently started working with GraphQL, or reviewed its pros and cons, you’ve no doubt heard things like “GraphQL doesn’t support caching” or

Making Your First Custom Svelte TransitionMaking Your First Custom Svelte TransitionMar 15, 2025 am 11:08 AM

The Svelte transition API provides a way to animate components when they enter or leave the document, including custom Svelte transitions.

Classy and Cool Custom CSS Scrollbars: A ShowcaseClassy and Cool Custom CSS Scrollbars: A ShowcaseMar 10, 2025 am 11:37 AM

In this article we will be diving into the world of scrollbars. I know, it doesn’t sound too glamorous, but trust me, a well-designed page goes hand-in-hand

Show, Don't TellShow, Don't TellMar 16, 2025 am 11:49 AM

How much time do you spend designing the content presentation for your websites? When you write a new blog post or create a new page, are you thinking about

What the Heck Are npm Commands?What the Heck Are npm Commands?Mar 15, 2025 am 11:36 AM

npm commands run various tasks for you, either as a one-off or a continuously running process for things like starting a server or compiling code.

Building an Ethereum app using Redwood.js and FaunaBuilding an Ethereum app using Redwood.js and FaunaMar 28, 2025 am 09:18 AM

With the recent climb of Bitcoin’s price over 20k $USD, and to it recently breaking 30k, I thought it’s worth taking a deep dive back into creating Ethereum

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment