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

Time:09-13

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 >
  <div id="dark-mode-btn">
  <button >test</button>
  <i  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

CodePudding user response:

I'd say use javascript, create a button and a javascript function onclick.

document.body.classList.toggle("dark-mode");

This function toggles the class dark-mode on the body, so for the darkmode style add body.dark-mode infront of all CSS selectors.

CodePudding user response:

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 >
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita, dolor?
    </header>
    <br>
    <div >
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Delectus facilis qui magnam quidem facere autem maiores
        necessitatibus, hic maxime eum.
    </div>
    <br>
    <span >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  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

  • Related