Search code examples
javascriptcssdarkmode

Switch between Light & Dark Mode


I have written a script using JavaScript that allows me to detect the user's preferred color mode and switch between light and dark mode using a button. But the whole thing has to be adjusted for each page.

Is there a simpler solution to both detect the preferred color mode and switch between the two modes using a switch (button)? Since CSS already has the prefers-color-scheme feature, I would only need to know how to switch between light and dark mode via a button as a user.

Here's my current code, written in plain JS:

window.onload = detectTheme()
function detectTheme() {
// This detects the device color mode when the user enters the webpage

    var theme = document.getElementById("theme");
    // Get the ID from the link we want to change

    if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
        theme.href = '/link/to/darkmode/file'
        // Changing the file based on the color mode ("dark" file for dark-mode)
    
    }
    else if (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches) {
        theme.href = '/link/to/lightmode/file'
        // Changing the file based on the color mode ("light" file for light-mode)
            
    }
}


var switchLD = document.getElementById("switch");
// This is the ID from the switch button

switchLD.onclick = function toggleTheme() { 

    var theme = document.getElementById("theme");

    // Checks what color-mode file is used
    if (theme.getAttribute('href') == '/link/to/lightmode/file') { 
        theme.href = '/link/to/darkmode/file'
        // Changing the file from light to darkmode
    }
    else if (theme.getAttribute('href') == '/link/to/darkmode/file') {
        theme.href = '/link/to/lightmode/file'
        // Changing the file from dark to lightmode
    }
}  


Any answer would help me a lot. If there is a solution using only CSS (or SCSS / SASS), I'd love to use it.

Solution

  • The comment by ThatPurpleGuy actually answered my question.

    In principle, prefers-color-scheme is not used. JS only detects whether the user is using dark or light mode and then adjusts a class in the body tag. Depending on which class is in the tag (light or dark), different CSS variables are applied.

    Here is the link to the YT Tutorial: https://www.youtube.com/watch?v=rXuHGLzSmSE