skip to Main Content

I made a button for dark mode, but when I leave the page, it goes back to light mode. How can I save the user’s choice so that when they go to another page they can continue in the mode they chose?

Js:

let trilho = document.getElementById('trilho')
let body = document.querySelector('body')

trilho.addEventListener('click', ()=>{
    trilho.classList.toggle('dark')
    body.classList.toggle('dark')

})

Css:

*{
    margin: 0;
    padding: 0;
    font-family: 'Poppins', sans-serif;
    box-sizing: border-box;
}

body {
    height: 100px;
    width: 100%;
    background-color: #fafafa;
}

/* DARK MODE */
.trilho {
    width: 70px;
    height: 30px;
    background-color: #6e6d6d;
    border-radius: 70px;
    position: relative;
    cursor: pointer;
}

.trilho .indicador {
    width: 30px;
    height: 30px;
    background-color: #000;
    border-radius: 50%;
    transform: scale(.8);
    position: absolute;
    left: 0;
    transition: .5s;
}

.trilho.dark {
    background-color: #c3c3c3;
}

.trilho.dark .indicador {
    left: 38px;
    background-color: #fff;
}

body.dark .container {
    background-color: #000;
}

body.dark footer {
    background-color: #000;
}

body.dark header {
    background-color: #000;
}

body.dark h1 {
    color: #fff;
}

body.dark a {
    color: #fff;
}

body.dark form{
    box-shadow: none;
}

body.dark .rodape{
    color: #fff;
}

HTML:


    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Website</title>
    
        <link rel="stylesheet" type="text/css" href="css/style.css">
        <script src="darkmode.js" async></script>
    
    </head>
    
    <body>
    
        <header>     
            <nav>        
             <ul class="nav-links">
                 <li><a href="/">link</a></li>
                 <li><a href="/">link</a></li>
                 <li><a href="#">link</a></li>
            </ul>    
    
    
          
              <div class="menu-hamb-button hide-on-desktop">
                <div class="btn-line"></div>
                <div class="btn-line"></div>
                <div class="btn-line"></div>
            </div>
           
            </nav>   
    
            <div class="trilho" id="trilho">
                <div class="indicador"></div>
            </div>
     
        </header>
    
        <div class="container">
             <h1>Website</h1>
        </div>
        <footer>
    
        <span class="rodape">Website</span>      
        </footer>
    
    </body>
    </html>

I tried some javascript commands for local storage, but they didn’t work in my html/css, maybe because the way I made my dark mode is different, I don’t know.

3

Answers


  1. let trilho = document.getElementById('trilho');
    let body = document.querySelector('body');
    
    // Check local storage for the user's theme preference
    const theme = window.localStorage.getItem("theme");
    
    // Set the initial theme based on localStorage
    if (theme === "dark") {
        body.classList.add("dark");
        trilho.classList.add("dark"); // Ensure the button reflects dark mode
    } else {
        trilho.classList.remove("dark"); // Ensure the button reflects light mode
    }
    
    // Add event listener to toggle dark mode
    trilho.addEventListener('click', () => {
        trilho.classList.toggle('dark');
        body.classList.toggle('dark');
    
        // Update localStorage with the current theme
        if (body.classList.contains("dark")) {
            window.localStorage.setItem("theme", "dark");
            trilho.classList.add("dark"); // Dark mode button
        } else {
            window.localStorage.setItem("theme", "light");
            trilho.classList.remove("dark"); // Light mode button
        }
    });
    * {
        margin: 0;
        padding: 0;
        font-family: 'Poppins', sans-serif;
        box-sizing: border-box;
    }
    
    body {
        height: 100px;
        width: 100%;
        background-color: #fafafa;
    }
    
    /* DARK MODE */
    .trilho {
        width: 70px;
        height: 30px;
        background-color: #6e6d6d; /* Light mode background */
        border-radius: 70px;
        position: relative;
        cursor: pointer;
    }
    
    .trilho .indicador {
        width: 30px;
        height: 30px;
        background-color: #000; /* Light mode ball */
        border-radius: 50%;
        transform: scale(.8);
        position: absolute;
        left: 0;
        transition: .5s;
    }
    
    .trilho.dark {
        background-color: #c3c3c3; /* Dark mode background */
    }
    
    .trilho.dark .indicador {
        left: 38px; /* Position for dark mode */
        background-color: #fff; /* Dark mode ball */
    }
    
    body.dark .container {
        background-color: #000; /* Dark mode container */
    }
    
    body.dark footer,
    body.dark header {
        background-color: #000; /* Dark mode footer and header */
    }
    
    body.dark h1,
    body.dark a,
    body.dark .rodape {
        color: #fff; /* Dark mode text color */
    }
    
    body.dark form {
        box-shadow: none; /* Dark mode form */
    }
     <header>
            <nav>
                <ul class="nav-links">
                    <li><a href="/">link</a></li>
                    <li><a href="/">link</a></li>
                    <li><a href="#">link</a></li>
                </ul>
                <div class="menu-hamb-button hide-on-desktop">
                    <div class="btn-line"></div>
                    <div class="btn-line"></div>
                    <div class="btn-line"></div>
                </div>
            </nav>
            <div class="trilho" id="trilho">
                <div class="indicador"></div>
            </div>
        </header>
    
        <div class="container">
            <h1>Website</h1>
        </div>
        <footer>
            <span class="rodape">Website</span>
        </footer>
    Login or Signup to reply.
  2. Didn’t you try localStorage() to make dark mode persist?

    • When the

      page loads, check the theme is set to dark. Then it applies the dark mode.

       `let trilho = document.getElementById('trilho');
       let body = document.querySelector('body');
      
       const theme = localStorage.getItem("theme");
       if (theme === "dark") {
           trilho.classList.add("dark");
           body.classList.add("dark");
       }
      
    • Every time when the user toggles the button, check the body has dark class. If it does save it on the localStorage,

      trilho.addEventListener(‘click’, () => {
      trilho.classList.toggle(‘dark’);
      body.classList.toggle(‘dark’);

       if (body.classList.contains("dark")) {
           localStorage.setItem("theme", "dark");
       } else {
           localStorage.setItem("theme", "light");
       }
      

      });

    Login or Signup to reply.
  3. All of the above answers are valid. You can look into the following

    The prefers-color-scheme CSS media feature is used to detect if a user has requested light or dark color themes. A user indicates their preference through an operating system setting (e.g. light or dark mode) or a user agent setting.

    You can use @media to detect the user-preferred theme and apply the colors accordingly. This article provides more information.

    @media (prefers-color-scheme: dark) {
      .theme-a.adaptive {
        background: #753;
        color: #dcb;
        outline: 5px dashed #000;
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search