Refreshing a page will disable dark mode

I'm in the process of implementing a dark mode for my website using the code below. However, I've encountered an issue where the dark mode resets when refreshing the page or navigating to a new page. I've heard about a feature called localstorage in JavaScript that might help with this problem. If anyone is familiar with it, could you please share the method to resolve this?

<style>
body {background-color: white}
body.dark {background-color: black}
button {background-color: white; color: black}
body.dark button {background-color: black; color: white}
</style>
<script>
function toggleDark() {
  const body = document.querySelector('body');
  if (body.classList.contains('dark')) {
    body.classList.remove('dark');
  } else {
    body.classList.add('dark');
  }
}

document.querySelector('#darkmode').addEventListener('click', toggleDark);
</script>
<button id="darkbutton" class="darkmode" onclick="toggleDark();myFunction()">Toggle dark mode</button>

Answer №1

To store data in JavaScript, consider using cookies or local storage. This allows you to retrieve the value even after refreshing the page. You can interact with local storage as shown below:

localStorage.setItem("theme", "light");

To access this data later, you can simply use:

localStorage.getItem("theme"); 

After refreshing the page, you will still be able to retrieve your theme setting.

Answer №2

The issue is arising because the user's choice is not being saved, causing it to reset to "light mode" each time the page loads.

To address this problem, you can store the data in localStorage or a cookie using JavaScript. This way, when the page is refreshed, you can retrieve the stored value and apply it to the document.

Using localStorage is recommended due to its ease of use compared to cookies with JavaScript.

The code snippet below demonstrates setting the key "theme" to "dark" with the setItem function, and retrieving it using the getItem function.

localStorage.setItem("theme", "dark");
localStorage.getItem("theme"); 

For more details on localStorage, refer to this helpful article on MDN: MDN localStorage Guide.

I have updated your code snippet below to incorporate these changes:


<html lang="en">
<head>
  <meta charset="utf-8">
  <style>
    body {background-color: white}
    body.dark {background-color: black}
    button {background-color: white; color: black}
    body.dark button {background-color: black; color: white}
  </style>
</head>
<body>
<button id="darkbutton" class="darkmode">Turn on dark mode</button>
<script>

const body = document.querySelector('body');
const button = document.querySelector('#darkbutton');
function toggleDark() {
  if (body.classList.contains('dark')) {
    body.classList.remove('dark');
    localStorage.setItem("theme", "light");
    button.innerHTML = "Turn on dark mode";
  } else {
    body.classList.add('dark');
    localStorage.setItem("theme", "dark");
    button.innerHTML = "Turn off dark mode";
  }
}

if (localStorage.getItem("theme") === "dark") {
  body.classList.add('dark');
  button.innerHTML = "Turn off dark mode";
}

document.querySelector('#darkbutton').addEventListener('click', toggleDark);
</script>
</body>
</html>

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

Issue: Unable to find solutions for all parameters in NoteService: (?)

After following a tutorial on Angular 2 from , I encountered the mentioned error when running my API. The browser indicates that there are unresolved parameters in the following service: import {Injectable} from '@angular/core'; import { ApiSe ...

The 'BaseResponse<IavailableParameters[]>' type does not contain the properties 'length', 'pop', etc, which are expected to be present in the 'IavailableParameters[]' type

After making a get call to my API and receiving a list of objects, I save that data to a property in my DataService for use across components. Here is the code snippet from my component that calls the service: getAvailableParameters() { this.verifi ...

stream a song with a font awesome symbol

Can an audio track be played using a font awesome icon, such as displaying the song name (mp3) with a play icon right next to it? When users click on the play icon, can the track start playing and be paused or stopped at will? The list will consist of app ...

Parsing HTML with Qt library isn't able to detect any elements

I am currently working on a web crawling application. Within the code, I have the following snippet: // Normally, the HTML content is retrieved from the web using QNetworkAccessManager & QNetworkReply: // QString htmlCode = this->reply->readAll( ...

Pushing state history causes browser back and forward button failure

I'm currently utilizing jQuery to dynamically load content within a div container. On the server side, the code is set up to detect if the request is being made through AJAX or GET. In order to ensure that the browser's back and forward buttons ...

Encountering a problem with ng-repeat when working with a JSON

Having a bit of trouble displaying the keys and values from a JSON object in an HTML table using ng-repeat. The JSON object is coming from the backend, but for some reason, it's not showing up on the frontend. I know there must be a simple mistake som ...

Regular expression: match all content up to a certain word(s)

I have two different versions of a string that look like this: The Student's Companion *Author: Alcock, Pete;May, Margaret;Wright, Sharon*MIL EAN/ISBN: 9781283333115 Java Programming: Java Expert*Author:Sarang, Poornachandra*MIL EAN/ISBN: 978128011 ...

Acquire information asynchronously in JavaScript while inside a for loop

Recently, I've been exploring this particular function snippet: function add_cnh(arr_clelem){ var id=arr_clelem.getElementsByClassName("present")[0].id; var date=arr_clelem.getElementsByClassName("present")[0].getAttribute('date'); v ...

Should I use Mongoose schema methods or prototype functions?

I am curious about the functionality of functions and ES6 classes in relation to new objects created from a mongoose schema. I wonder if the functions are duplicated for each new object and what the best approach is when utilizing ES6 classes. To illustrat ...

Is it possible to execute a function within an HTML page simply by clicking on it?

As someone who is new to the world of HTML, CSS, and JS, I'm currently facing a challenge: On my website's page1.html, I have implemented a feature that allows users to sort different articles on the page by selecting a sub-menu from the navigat ...

Execute a function upon pressing the enter key

Currently, I am working on coding a webpage with a form that includes one field where users input a set of numbers. After typing in the numbers, they should then press a button labeled 'Run' to execute the code. However, the issue arises when use ...

Exploring cross-domain loading and AJAX with JQuery

My process for loading items on is as follows: Starting with JQuery via Google API Next, I load two global functions from another domain: loadcrossdomain (using getJSON via query.yahooapis) and a simple function for URL parsing Inclusion of Googl ...

Utilizing Node Js and Socket.Io to develop a cutting-edge bot

Is it possible to run JavaScript with Node.js without launching Google Chrome from various proxies? Can someone provide a sample code for this task? For example, you can find a similar project here: https://github.com/huytd/agar.io-clone Another project c ...

Is there a way to retrieve the current state of a Material UI component in a React functional component without needing to trigger an event by clicking on

Seeking a way to retrieve current values of Material Ui components without the need to click on any event after page reloads or DOM changes. These values are pulled from a database. My goal is to confirm whether the values have been updated or not by chec ...

Using Vanilla JavaScript to Disable a Specific Key Combination on a Web Page

On a completely random English-Wikipedia editing page, there exists a way to add content (for example, "test") and save it using the existing key combination of Alt+Shift+S. My goal is to specifically prevent this action without removing the save button b ...

What is the best way to ensure the menu background aligns perfectly with the header in HTML/CSS?

Issue: Menu background doesn't align with header. (visible in the image provided below) VIEW IMAGE Any suggestions on how to resolve this alignment problem? CSS CODE : .header { margin:0px auto; max-width: 960px; } #header { height:30 ...

Encountering an error with the message "SyntaxError: missing ; before statement" while attempting to utilize the Google Place Search

Lately, I've been encountering a 'SyntaxError: missing ; before statement' error while attempting to execute this ajax code in order to retrieve all nearby ATMs within a 1 km radius. var url = "https://maps.googleapis.com/maps/api/place/nea ...

What is the purpose of re-checking the user in the passport.deserializeUser function?

After reading multiple articles on how to utilize passport.js, I'm left wondering why user verification is repeated within the passport.deserializeUser function. The code snippet looks like this: passport.deserializeUser((id, done) => { console. ...

Encountering issues with resolving dependencies in webdriverIO

I'm attempting to execute my WebdriverIo Specs using (npm run test-local) and encountering an error even though I have all the necessary dependencies listed in my package.json as shown below: [0-2] Error: Failed to create a session. Error forwardin ...

Nuxt.js Development Script Fumbles

Recently, I've been working on a website using Nuxt.js and have been really enjoying the process. However, I'm encountering an error that's puzzling me whenever I attempt to run $npm run dev: 0 info it worked if it ends with ok 1 verbose cl ...