-1
const btn = document.querySelector(".dark_mode_btn button");
const element = document.querySelectorAll("div, h2, html");
    

$(btn).click(function(){
    if($(element).hasClass('dark_mode'))
   {
      $(element).removeClass('dark_mode');
            
    } else{
      $(element).addClass('dark_mode');
           
    }
});

My code can't save when I move to other pages. How can I save thoes in localstorage?

suesoo
  • 9
  • 1
  • store it in localStorage – Pranav C Balan Jun 15 '21 at 07:09
  • You can store the setting of the page in the localStorage. Once you load the page again, you can fetch the setting in the localStorage. [MDN localstorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) – ikhvjs Jun 15 '21 at 07:10

2 Answers2

1

You can use JavaScript's localStorage to save the preference.

You can store a string ('true'/'false') and check on page load.

Something like this will help:

let darkMode = localStorage.getItem("dark-mode");
//darkMode will be a string
if(darkMode != null && darkMode === 'true'){
    $(element).addClass("dark_mode");
}

use localStorage.setItem() to set the value. Ex: localStorage.setItem("dark-mode","true"); or localStorage.setItem("dark-mode","false");

more info here: Storing Objects in HTML5 localStorage

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
ahsan
  • 1,409
  • 8
  • 11
0

You can simply add that in the localStorage using .setItem() method of the localStorage and you can retrieve same using .getitem() method. Please find below code to

const btn = document.querySelector(".dark_mode_btn button");
const element = document.querySelectorAll("div, h2, html");
    

$(btn).click(function(){
    if($(element).hasClass('dark_mode'))
   {
      $(element).removeClass('dark_mode');
      localstorage.setItem("darkModeEnabled","true")
            
    } else{
      $(element).addClass('dark_mode');
      localstorage.setItem("darkModeEnabled","false")     
    }
});
// To get the Item use localStorage.getItem('darkModeEnabled');

Please make sure to store only string/boolena type data in the storage as it only accepts stringified data.For objects please stringify data using JSON.stringify()

Note : I would suggest to load these values from database instead of storage as you will loose the information once user logout/session-ends or clears the storage.

Nimantha
  • 6,405
  • 6
  • 28
  • 69