What are some effective ways to utilize localstorage efficiently?

I've been working on creating a variable that stores its value across multiple pages using local storage. However, I've encountered an issue where the variable is not being saved, and there are no error messages to help diagnose the problem.

Here are the steps I've taken before reaching out for help: I watched YouTube tutorials on using local storage. I referenced this website . I also searched for solutions on Stack Overflow.

Unfortunately, I have been unable to find a solution to this issue.

Variables.js file

var mode = "light";

localStorage.setItem('mode', '');

function draw(){
  
  if (document.body.style.backgroundColor == "#181818"){
    mode = "dark";
    console.log(mode);
  }
  
  if (document.body.style.backgroundColor == "#f2f112" || mode == "dark"){
    mode = "dark";
    alert("Error while attempting to change background to dark theme.")
  }

}

index.html file

<!DOCTYPE html>
<html>
  <head>
  <title>Home</title>
  </head>
  <body>
  <p><a href="settings.html">Settings</a></p>
    <script type="text/javascript"></script>
    <script src="variables.js"></script>
    <script src="settings.html"></script>
    <script>

    modeselect = localStorage.getItem(mode);

    if (modeselect == "light"){
      console.log("light mode");
      document.body.style.backgroundColor = "#f2f112";
    }
    if (modeselect == "dark"){
      console.log("dark mode");
      document.body.style.backgroundColor = "#f2f112";
    }

  </script>
    </body>
</html>

settings.html file

<!DOCTYPE html>
<html>
  <head>
    <title>Settings</title>
  </head>
  <style>
  .button1 {
  background-color: #444444;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
}
  .button2 {
  background-color: #ffffff;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
  }
  body {
    background-color: rgb(156,158,158);
  }
</style>

<body>
<form>
  <input type="button" class="button1" value="Dark mode" onclick="darkmode()">
  <input type="button" class="button2" value="Light mode" style ="color:black;" onclick="lightmode()">
</form>
<p><a href="index.html">Home</a></p>
<script src="variables.js"></script>
<script>
localStorage.getItem('mode');
function darkmode() {
  mode = "dark";
  alert(mode);
  if (mode == "light"){
    alert("error while changing theme");
  }
  if (mode == "dark"){
  alert("successfully changed to dark mode");
  document.body.style.backgroundColor = "#181818";
  }
}
function lightmode() {
  mode = "light";
  alert(mode);
  if (mode == "light"){
    alert("successfully changed to light mode");
    document.body.style.backgroundColor = "#9c9e9e";
  }
  if (mode == "dark"){
    alert("error while changing theme");
  }
}
</script>
</body>
</html>

Answer №1

It appears that you have not stored any value in your local storage. Your current local storage value seems to be empty.

To set a value in local storage, you can use the "localStorage.setItem" method with the key "mode". Here is an example:

localStorage.setItem('mode', mode);

To retrieve the stored value, you can use the localStorage.getItem('mode') method.

Answer №2

document.body.style.backgroundColor = localStorage.getItem('mode') || "gray";
function darkmode() {
    mode = 'black'
    document.body.style.backgroundColor = mode;
    localStorage.setItem('mode', mode);
}
function lightmode() {
    mode = 'white'
    document.body.style.backgroundColor = mode;
    localStorage.setItem('mode', mode);
}
[type="button"] {
    border: none;
    padding: 15px;
    font-size: 26px;
    margin: 4px;
    cursor: pointer;
    outline: none;
    border: 2px solid red;
}
<input type="button" style ="color:black;background-color: white;"  value="Light mode" onclick="lightmode()">
<input type="button" style ="color:white;background-color: black;" value="Dark mode" onclick="darkmode()">

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 best way to destructure an array enclosed within the Promise keyword in JavaScript?

Currently, I am attempting to extract information from a PSQL table using the following code: async function requestData() { var selectQuery = `SELECT "fName", "lName", "phoneNumber", "eMail" FROM public."Use ...

Show the total sum of a specific column in a datatable and enable the option to export the data to an Excel

When exporting a datatable as an Excel file with 4 columns, the third column contains product prices. After the export, I would like to see an additional row at the end of the table labeled "Total" that displays the sum of all values in column 3. I initia ...

Ways to retrieve an element from an array

I need help finding the right way to retrieve the value of the message "Meeting 9943...is not found or has expired". Here's what I tried: if (response.data.status == 404) { angular.element(document.getElementById("msg")).css("color", "red"); ...

"Unlocking the Potential of ReactJS: A Guide to Setting Focus on Components Once They Become

My code had a <div> with a child component named SocialPostwithCSS, and when onClick was triggered, it would hide the div, set the state to editing: true, and display a <textarea>. I used this.textarea.focus with a ref={(input)=>{this.textar ...

Issues arise when attempting to use Stylus in conjunction with React

I am currently working on developing a web application that utilizes Stylus and React. I have successfully rewritten all the Stylus language files, but I am encountering an issue where the React components are not being styled as expected. Below is one of ...

Struggling to properly render JSON data

Having trouble accessing specific elements in a script that merges local JSON files using AJAX? The script works fine in Chrome Console, but you can't reach certain elements like 'object.country'. Any suggestions on how to tackle this issue? ...

Having trouble with Laravel 5.8 Bootstrap integration within JQuery?

i found a helpful resource at everything seems to be working well in the view, but i'm encountering issues when trying to implement it in JQuery. if anyone has suggestions on how to resolve this problem, please let me know. here is the PHP code for ...

After updating the state, the Next.js axios call experiences a delay before executing the desired action

I am currently working on a NextJS project that relies on Axios for handling API calls. Within this project, there is a loading state implemented to show a loading spinner when making these API calls. However, I have encountered an issue where after click ...

"Looking to replace a character class pattern using regex in JavaScript? Here's how you can easily

I have a string: "\W\W\R\" My goal is to transform this string using regular expressions into: <span>W</span><span>W</span>\R This is the code I'm currently using: "\W\W\R".replace(/&b ...

What is the best way to verify the type of an object received from request.body in Typescript

Is it possible to check the object type from the request body and then execute the appropriate function based on this type? I have attempted to do so in the following manner: export interface SomeBodyType { id: string, name: string, [etc....] } ...

Capture data from a Telegram bot and store it in a Google Sheet

I am trying to use a spreadsheet through a Telegram bot as a TODO list so that when I input something on my phone, it is saved in the spreadsheet. (I'm following this tutorial https://www.youtube.com/watch?v=XoTpdxbkGGk, which seems accurate with Goog ...

Guide on how to "attach" the routes of an Angular 2 module to a specific location within the routing structure

Let's consider a scenario where the main routing module is defined as follows: // app-routing.module.ts const appRoutes: Routes = [ { path: 'login', component: LoginComponent }, { path: 'auth', ...

Put a watch on a variable as soon as it is set

When initializing a variable, I want to use the $watch function in Angular without it automatically initializing right away. Is there a way to accomplish this? $watch $scope.$watch(function () { return $scope.character.level; }, function (ne ...

Issues encountered with sending post requests to a yii2 application when using Angular4

After implementing the following code: this.http.post('http://l.example/angular/create/', {name: 'test'}).subscribe( (response) => console.log(response), (error) => console.log(error) ); I encountered an error on ...

I am looking to send a combination of string and HTML data to the controller when using the Summernote editor in MVC

As a beginner in MVC development, there are certain aspects that I am still struggling with. Currently, I am using the Summernote Editor to compose blog posts and Ajax to submit them. However, I encountered an issue when trying to send both HTML data from ...

Using Jquery to automatically populate an input field if the user already exists

I'm currently working on populating a form if the user input for name and firstname already exists in my database. However, I am facing an issue with my JavaScript program where it fails to check if the name and firstname combination already exists i ...

Can Mutation Observer be utilized in conjunction with a Three.js element in an A-Frame environment?

export class ColliderComponent { constructor() { this.observer = this.createMutationObserver(); this.registerAframeComponent(); } //Registers the AFRAME component. registerAframeComponent(){ const self = this; AFRAME.regi ...

The success callback is not triggered when making a JSONP request

I have a specific URL that returns JSON data when accessed through a browser or REST client. However, I am having trouble making the request using jQuery in my express server running over HTTPS. Despite receiving a successful response in the network debug ...

Can you explain the purpose of $winstonLoggerConfig<T>() and $winstonLogger<T>() in winston v3?

I'm currently using the winston logger and I want to implement flow typing for it. However, I am unsure of what exactly I should pass to it in order to achieve this. Below is my current logger setup: const logger = createLogger({ ... }); Missing typ ...

The use of async components in Vue.js with named imports

I understand how to dynamically load components asynchronously in Vue. For example, instead of importing MyComponent directly: import MyComponent from '@/components/MyComponent' export default { components: { MyComponent } } We can use ...