Skip to content
Advertisement

Add button to switch between light and dark mode using two prefers-color-scheme

I have created a page with complex design and different background colors and I decided to add a button to let users switch between light and dark mode

I’ve tried different solutions with JS, but with no success. The current workaround I use is adding two media in my CSS file. Basically, if my website appearance is set to Dark, the page will also load dark-styled theme, and Light for Browser Light Appearance.

@media screen and (prefers-color-scheme: dark)
@media screen and (prefers-color-scheme: light)

Question is: How can I let users manually change between dark-light color-schemes manually with a button using vanilla Javascript? (not with the checkbox) P.s. Maybe I could somehow implement this with var(–rule) in CSS but I’m still new to this stuff and I have almost zero JS knowledge

For example:

@media screen and (prefers-color-scheme: dark) {
    p, h2 {
        color: #e7e7e7;
    }
@media screen and (prefers-color-scheme: light) {
    p, h2 {
        color: #333333;
    }

html button (i class/button is a placeholder)

<div class="dark-mode-container">
  <div id="dark-mode-btn">
  <button class="theme-switch">test</button>
  <i class="fa-solid fa-moon" title="Switch to Dark mode"></i>
</div>

Here is my button inside sticky nav which I plan to use to switch modes dark mode button inside nav bar

Advertisement

Answer

const btn = document.getElementById('btn');
        btn.addEventListener('click', function () {
            var elmWitchChange = document.getElementsByClassName('light')
            for (var i = 0; i < elmWitchChange.length; i++) {
                elmWitchChange[i].classList.toggle('dark')
            }
        })
  .dark {
            background-color: black;
            color: white;
        }
 <header class="light">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita, dolor?
    </header>
    <br>
    <div class="light">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Delectus facilis qui magnam quidem facere autem maiores
        necessitatibus, hic maxime eum.
    </div>
    <br>
    <span class="light">Lorem ipsum dolor sit amet consectetur adipisicing elit. Eligendi, recusandae?</span>
    <br>
    <div>
        this div does not have a light class therefore it won't be effected
    </div>
    <br>
    <button class="light" id="btn">toggle</button>
in my opinion: if you want to make multiple elements react to your actions you can make a common class and use it so you can change their style
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement