Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can anyone give me an easy way of making a darkMode and lightMode on a HTML page using Javascript?

I’m trying to make a website but I’m having trouble making a dark/light theme using JS. Does anyone know an easy way to make a dark/light theme?

  • My idea is fetching elements with a certain style and changing it’s CSS color property.

I tried using document.getElementsByClassName() but it made too much of a hassle. It’s also really inefficient.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Define your colours using custom properties.

(You will want more colours than this example)

body {
    --main-bg-color: yellow;
    --main-fg-color: black;
}

Then override them in a dark mode stylesheet:

@media (prefers-color-scheme: dark) {
    body {
        --main-bg-color: black;
        --main-fg-color: yellow;
    }
}

Then, if you want the user to be able to toggle with your own UI as well as using their system wide choice, define them again with a class:

body.lightMode {
    --main-bg-color: yellow;
    --main-fg-color: black;
}

body.darkMode {
    --main-bg-color: black;
    --main-fg-color: yellow;
}

Then just use those variables when you want color name:

h1 {
    color: --main-bg-color;
}

If you want the UI to change the style then:

function eventHandler() {
    const b = document.body;
    if (b.classList.contains("darkMode")) {
         b.classList.remove("darkMode");
         b.classList.add("lightMode");
    } else {
         b.classList.remove("lightMode");
         b.classList.add("darkMode");
    }
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading