Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I toggle dark mode using JavaScript?

I am using prefers-color-scheme: dark to create a dark theme in CSS (it applies to Safari in macOS v10.14 (Mojave)). Is there a way to force the page to use my dark mode code on other browsers that don't support it, like the following?

document.querySelector('#toggleDarkMode').addEventListener('click', function () {
    -- Force page to use dark mode defined in CSS
})
like image 386
Anton Webb Avatar asked Oct 24 '19 13:10

Anton Webb


2 Answers

No.

A workaround is to move every property that changes to a custom property.

Then you can do something like:

p {
    color: var(--body-colour);
}

And combine it with:

/* default, light scheme */
body {
    --body-colour: black;
}

@media (prefers-color-scheme: dark) {
    body {
        --body-colour: white;
    }
}

body.light-mode {
    --body-colour: black;
}

body.dark-mode {
    --body-colour: white;
}

Then your JavaScript just needs to add a light-mode or dark-mode class to the body element to force that mode (overriding the default (if the browser doesn't support the feature, or if it is set to light mode) or the dark mode media version).

like image 133
Quentin Avatar answered Sep 30 '22 04:09

Quentin


I'm guessing you're using media-queries to know if the browser / OS is set to dark-modus. If older browsers don't understand the media-query they will skip it all together. This is often used to make browser specific 'hacks'.

A way to make it work is to set the sass code outside the query within a general class that you can add to the <body> tag. You can store this preset within localStorage or cookies so it won't reset on a page reset.

About localStorage: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

I would make the current sass code a mixin so you won't need to declare it a second time and make your code easier to maintain. More info about it: https://sass-lang.com/documentation/at-rules/mixin

like image 35
Arno Tenkink Avatar answered Sep 30 '22 04:09

Arno Tenkink