color-scheme: dark light; and user enabled theme change with JS

Hi, I want to ask what the best way to do the following is:

1. I want to use
color-scheme: dark light;
,
2. have JS recognize which scheme the user has enabled
3. based on which scheme the user has, a button would be used to change to the opposite theme.
4. I do not want to additionally define what dark/light theme would be like, like we would usually do without color-scheme in CSS.


so I have this code
html {
  color-scheme: dark light;
}

ChatGPT says I should have additionally defined what dark/light theme would be like, like we would usually do without color-scheme in CSS - which I do not want.
        html[data-theme="light"] {
            background-color: white;
            color: black;
        }

        html[data-theme="dark"] {
            background-color: black;
            color: white;
        }


so with JS , I would detect their scheme and change the theme, but now it is made by calling to "data-theme" (which I don't know what it is) and calling on the additionally CSS definitions of dark and light (which I do not want to use).

// Detect the user's preferred color scheme
        var prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)").matches;

        // Set the initial theme
        var currentTheme = prefersDarkScheme ? "dark" : "light";
        document.html.setAttribute("data-theme", currentTheme);

        // Add a listener for the button click
        document.getElementById("theme-switcher").addEventListener("click", function() {
            // Toggle the color scheme
            currentTheme = currentTheme === "dark" ? "light" : "dark";
            document.html.setAttribute("data-theme", currentTheme);
        });
Was this page helpful?