1

I've added dark mode to my website and it works perfectly

But just after I refresh my page the default view that is Day Mode is shown.

so, is there any way to save this preferences?

HTML

    <body>
    <div class="main-page" id="main-page">
        <a id="darkmode" onclick="myFunction()" style="display: block; position: fixed; z-index: 2147483647;"><span><i class="fa fa-moon" id="darkIcon"></i></span></a>
    </div>
</body>

JavaScript

    function myFunction() {
    var element = document.getElementById("main-page");
    var icon = document.getElementById("darkIcon");
    element.classList.toggle("active-dark");

    if (element.className == ["main-page active-dark"]){
        if (icon.className == "fa fa-moon"){
            icon.classList.toggle("fa-sun");
        }else {
            icon.classList.toggle("fa-moon");

        }

    }
    if (element.className == "main-page"){
        if (icon.className == "fa fa-sun"){
            icon.classList.toggle("fa-moon");
        }else {
            icon.classList.toggle("fa-sun");

        }


    }
}

NOTE :

To activate dark mode i just add "active-dark" after "main-page" class and to disable dark mode i just remove the class

ali ahmed
  • 11
  • 1
  • 3
  • Does this answer your question? [How to create a session using JavaScript?](https://stackoverflow.com/questions/2257631/how-to-create-a-session-using-javascript) – Alon Eitan May 27 '20 at 16:00
  • https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage – Adrian May 27 '20 at 16:00
  • `@media (prefers-color-scheme: dark) { /* adjust css for dark mode */ }` https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme – connexo May 27 '20 at 16:06

4 Answers4

2

In your myFunction function save state of darkmode in localStorage

function myFunction() {
     localStorage.setItem('isDarkMode', true);

And in your JS add following line

Just make sure DOM is loaded before execution of this line

if (localStorage.getItem('isDarkMode') === 'true') {
    document.getElementById('main-page').classList.add('active-dark');
} 
Kiran Shinde
  • 5,732
  • 4
  • 24
  • 41
  • could you please give me a full example because i'm beginner in js – ali ahmed May 27 '20 at 16:13
  • Full example? You just have add these two lines in your code. First line in your `myFunction`. Well the second if condition you can add multiple places. 1) `DOMContentLoaded` callback 2) At the end of your body in ` – Kiran Shinde May 27 '20 at 16:18
1

Here is the full code to auto-detect user dark mode and save it to local storage for keeping the current mode throughout the session.

The below code will run when the user clicks the dark mode toggle button. Make sure you create the CSS class for .dark-mode with the required CSS code.

$(document).ready(function () {

   $("#dark-mode").click(function () {
      $("body").toggleClass("dark-mode");
      if (localStorage.hasOwnProperty('isDarkMode')) {
         if (localStorage.getItem('isDarkMode') === 'true') {
            localStorage.setItem('isDarkMode', 'false');
         }
         else if (localStorage.getItem('isDarkMode') === 'false') {
            localStorage.setItem('isDarkMode', 'true');
         }
      }
   })


   if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
      if (!(localStorage.hasOwnProperty('isDarkMode'))) {
         $("body").addClass("dark-mode");
         localStorage.setItem('isDarkMode', true);
      }
   }
   else {
      if (!(localStorage.hasOwnProperty('isDarkMode'))) {
         $("body").removeClass("dark-mode");
         localStorage.setItem('isDarkMode', false);
      }
   }

   if (localStorage.hasOwnProperty('isDarkMode')) {

      if (localStorage.getItem('isDarkMode') === 'true') {
         $("body").addClass("dark-mode");
      }
      else if (localStorage.getItem('isDarkMode') === 'false') {
         $("body").removeClass("dark-mode");
      }
   }
})
Praveen Kumar
  • 849
  • 8
  • 8
0

This depends on where you render (generate the html) your page.

If you render it on the client (browser) you can save it in the session storage:

sessionStorage.setItem("darkmode", true)

and then get it when loading your page via:

sessionStorage.getItem("darkmode")

If you render it on the server you can save it in a session variable. This depends however heavily on your server side library / language which you use to implement this. You would then make a request to the server in order to set this variable.

An alternative is to use a cookie. You can read this on the server and on the client. You can set it like this.

document.cookie = "darkmode=true"

EDIT:

You should use the local storage since it will outlive the session.

localStorage.setItem("darkmode", true)

and

localStorage.getItem("darkmode")
Arwed Mett
  • 2,614
  • 1
  • 22
  • 35
0

My take:

                        <style>
                        .dark-mode {
                          background-color: black;
                          color: white;
                        }
                        </style>
                    <div>
                        <button class="btn btn-light btn-sm" onclick="myFunction()">Toggle dark mode</button>
                        <script>
                        function myFunction() {
                            if (localStorage.getItem('isDarkMode')=='true'){
                                localStorage.setItem('isDarkMode', false)} 
                                else 
                                {localStorage.setItem('isDarkMode', true)}
                                toggle_color();
                        };

                        function toggle_color(){
                            if (localStorage.getItem('isDarkMode')=='true'){
                            
                            document.getElementById('main').classList.add('dark-mode');
                        }
                        if (localStorage.getItem('isDarkMode') === 'false'){
                                
                            document.getElementById('main').classList.remove('dark-mode');
                            };
                        }
                        toggle_color()
                        </script>
                    <div>
Arindam Roychowdhury
  • 5,927
  • 5
  • 55
  • 63