Storing Dark Mode Preference in Local Storage using JavaScript

I recently implemented dark mode on my website and it's working flawlessly.

However, every time I refresh the page, it reverts back to the default Day Mode view. Is there a way to save these preferences?

In the HTML section:

    <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>

And in the JavaScript section:

    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");

        }


    }
}

Please Note:

To switch to dark mode, simply add "active-dark" after the "main-page" class, and to go back to light mode, remove the class.

Answer №1

To keep track of the dark mode state within your myFunction method, store it in the browser's localStorage.

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

Then, include the following line in your JavaScript code.

Ensure that the DOM has finished loading before running this line of code.

if (localStorage.getItem('isDarkMode') === 'true') {
    document.getElementById('main-page').classList.add('active-dark');
} 

Answer №2

Check out this complete code snippet to automatically detect the user's preference for dark mode and store it in local storage to maintain the current mode during their session.

When the user interacts with the dark mode toggle button, the following code will be executed. Remember to define the CSS class .dark-mode with the necessary styling.

$(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");
      }
   }
})

Answer №3

The location where you generate your HTML page will determine how to handle saving data for dark mode.

If the generation happens on the client side (browser), you can store it in session storage like this:

sessionStorage.setItem("darkmode", true)

To retrieve it when loading the page, use:

sessionStorage.getItem("darkmode")

If the rendering occurs on the server side, saving it in a session variable would be necessary. The method may vary based on the server-side technology being used. A request to the server would then be required to set this variable.

Another option is using a cookie, which can be accessed both on the server and the client side. Set a cookie with this code:

document.cookie = "darkmode=true"

UPDATE:

It's recommended to use local storage instead of session storage because it persists beyond the current session. Here is how to save data in local storage:

localStorage.setItem("darkmode", true)

and retrieve it with:

localStorage.getItem("darkmode")

Answer №4

Here is my personal viewpoint:

                        <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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the method for shifting content as the window is resized to ensure it remains in its original position?

My page features a grid with three div elements. Each div is the size of the viewport, resulting in only one div being visible at a time, while the other two remain outside the view. This makes the grid three times larger than the viewport. When resizing ...

Accessing target.com using a script for login

Being a beginner in the programming world, I am currently working on creating a basic login script that can log me in to target.com when executed. In the future, I plan to add more functionalities to it, but I am struggling to find the optimal approach. ...

WebGl - Perspective skewing perspective

I've been working on implementing an oblique projection in WebGL, but I'm encountering an issue where the projection appears identical to ortho. Here's the snippet of code setting up the projection matrix: mat4.identityMatrix(pMatrix); ...

Ways to eliminate the blue selection box when dragging canvas objects in fabric framework

I've been trying to find a solution to remove the annoying blue highlight box that appears when dragging on the canvas while using fabric js, but so far I haven't had any luck. I've tried the following code, but it only works for text and n ...

Tips for retrieving a variable from an XML file with saxonjs and nodejs

I came across an xml file with the following structure: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE agent SYSTEM "http://www.someUrl.com"> <myData> <service> <description>Description</description> < ...

Unlocking the potential of # to craft interactive web pages

Lately, I've been seeing more and more websites like Twitter that have integrated AJAX into their layouts. One thing that has really piqued my interest is the inclusion of #! in URLs. I'm curious about how I can implement this on my own site or w ...

I am curious as to how this function is aware of the specific attribute that is being passed

I've been experimenting with a little application that fetches a list of movies from an API. You input a word and it returns all movies with that word in the title. Here's the code responsible for fetching the list: var getMovies = function (que ...

What is the best way to increase a specific value in an array of objects once it has been located (using findOne()), but before it is

I'm looking for a more efficient way to update an object within an array of schemas in one database request instead of two. Currently, I use findOneAndUpdate() to increment the field if the object already exists, and then I have to use update() if the ...

Is there a way to easily access the automated departure range feature of a date

I apologize if my question seems too simple, but I am having trouble understanding JavaScript. My issue pertains to a range datepicker where I want the departure picker to automatically open when the arrival is selected. Here's the JavaScript code I h ...

Struggling to populate dropdown with values from array of objects

My issue is related to displaying mock data in a dropdown using the SUIR dropdown component. mock.onGet("/slotIds").reply(200, { data: { slotIds: [{ id: 1 }, { id: 2 }, { id: 3 }] } }); I'm fetching and updating state with the data: const ...

Tips for displaying ajax search results in Laravel views

My attempt to send a JSON response via AJAX to my Laravel view is not yielding any successful results. public function viewMasakanAjax(Request $request) { if($request->ajax()) { $alberMasakan = Masakan::where('alber_nama_masakan&ap ...

What is the best way to implement form fields that have varying validation patterns based on different conditions?

Currently, my focus is on developing a form that prompts the user to choose between "USA" or "International" via radio buttons. The input field for telephone numbers should then adapt its requirements based on the selected country - either a 10-digit US nu ...

Tips for organizing multiple TextField components within a Grid container using Material-UI

I utilize Material-UI for my front-end design needs. I have a query related to the Grid layout feature. My goal is to include 7 TextField elements, but they are appearing overlapped. When I modify all 7 TextField elements from xs={1} to xs={2}, they become ...

Link specifically for the ADFS 2.0 single sign-on application

I've been conducting research on both Google and Stackoverflow but haven't been able to find a solution to my problem. Within my ADFS portal, there are 5 different services that can be selected. I'm trying to determine how I can generate a ...

What could be causing the function to return undefined when using fetch, axios, ajax, or a promise?

When using asynchronous calls, the issue arises where the response is returned as undefined instead of the expected data. This problem can be seen in the following scenarios: Using Fetch const response = getDataWithFetch(); console.log(response); fun ...

There seems to be a discrepancy with the IP to hex conversion equation in my JavaScript code. The result I'm getting doesn't align with what other

How to check if an item is a valid IP address (e.g. 254.253.242.222)? `var h0 = Math.pow(256,0);` `var h1 = Math.pow(256,1);` `var h2 = Math.pow(256,2);` var h3 = Math.pow(256,3); var splitup = item.split('.'); var iHex = ...

What is the functionality behind a free hosting website?

Is anyone familiar with websites like Hostinghood, where users can create a subdomain and upload HTML, CSS, etc.? I'm curious about how they operate and how I can create a similar site. This is my first question here, so please respond instead of disl ...

Understanding sessionToken functionality and enabling multiple device logins for a single user simultaneously in Parse

Is there a way to stay logged in as the same user on multiple devices? I have an Android app and a web app and would like to be able to be logged in on both simultaneously. However, when I try to do so, I am receiving an error message 209 stating "invali ...

Having issues with email verification and the length of phone numbers not functioning properly

I need to validate two text fields before registration: the email must be in correct format and the number must have exactly 11 digits. Any mismatches should trigger an error message. For the email validation, I used a function that checks for the require ...

Guide to retrieving a specific cookie value with socket.io

I have successfully retrieved all cookies using the socket.request.headers.cookie. Upon console logging, the output appears as follows: PHPSESSID=mtklg8k81cpkop5ug6aechbb34; user=77; io=1Klg6xgTRXhb2OWiAAAA Now, I am trying to extract only the value of ...