Home  >  Article  >  Web Front-end  >  Change Light and Dark theme in just lines of JavaScript

Change Light and Dark theme in just lines of JavaScript

王林
王林Original
2024-08-21 21:05:06768browse

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">

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