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

Tips for making a background image responsive using ng-style in AngularJS

Can anyone assist me in fixing the gap space issue in a responsive view with an attached jpg background image? Follow this link for more details: enter image description here ...

Making Node.js Wait Until a Function Completes its Execution

Currently, I am using a for-loop in Node.js to run the x() function from the xray package. This function scrapes data from webpages and then writes that data to files. The program works well when scraping around 100 pages, but I need it to handle around 10 ...

An error was encountered in customizing CKEditor5 in Vue: compilation unsuccessful

I tried to integrate a custom CKEditor5 into my Vue application, but encountered a failed to compile error. I generated the custom build using the online tool provided by CKEditor. Subsequently, I placed the files in a new folder called ckeditor within th ...

Is there a way to deliberately trigger an error using Selenium WebDriverIO?

Is there a way to trigger an error using ChromeDriver with Selenium WebDriverIO? I'm not sure if there's a method like browser.fire('error'). ...

Changing the z-index using createjs

Is there a way to ensure that the dragged item always stays on top when moved? How can I prevent it from getting dragged underneath another object? Can I specify which "sequenceNumbers" should be moved to the top of the sorting order? //++++++++ ...

Utilization of z-index with float: left within an image gallery in CSS

Currently, I am working on an image gallery that has content generated randomly. In terms of CSS, the images are positioned using the following code: .item { width: 200px; margin: 10px; float: left; } To add some functionality, I have implemented ...

Update a section of my PHP webpage using setInterval()

How can I refresh a PHP value every second using setInterval()? I am familiar with refreshing values in HTML, but now I want to do the same with PHP values. Here is my code: <script> setInterval(function() { <?php $urlMachineOnline = ' ...

What is the best way to convert a date to ISO 8601 format using JavaScript? Are there any built-in functions or methods in

Currently, I am using this function to set the duration: const setDuration = () => { const currentDate = new Date(); const newDate = new Date(currentDate.getTime()); const year = newDate.getUTCFullYear(); const m ...

Clearing HTML input connected to PHP and AJAX: A handy guide

Is there a way to automatically clear my HTML input after pressing the enter key? I have a complex program that utilizes AJAX and PHP. I attempted to use jQuery's $("#txt").val('') function, but it clears every letter typed (I only want to c ...

Altering the text and functionality of buttons with jQuery

A JavaScript method I have is designed to change based on the state of a button, which is determined by using indexOf("..some text.."). $('#add1').click(function(){ if($(this).text().indexOf("Add Me!")) { $.ajax({ type: & ...

Listcell XUL with button options

How can I make buttons inside a listcell function in XUL? I am having trouble getting it to work. Here is the XUL code: <listitem id = "1"> <listcell label = "OK Computer"/> <listcell label = "Radiohead"/> <listcell label ...

Interacting div elements with jQuery's dynamic content

I am searching for a way to populate a div with content based on my click selection. To begin, I create a dynamic table like the one below: user name total hours worked button(unique id fetched from database) user name total ho ...

Creating custom designs for a HTML button using CSS

Within an HTML form, there are two buttons set up as follows: <button kmdPrimaryButton size="mini" (click)="clickSection('table')">Table View</button> <button kmdPrimaryButton size="mini" (click)=&quo ...

Can MUI 5 replicate the Emotions 'css' function through analog?

From what I've learned, MUI 5 utilizes Emotion for its styling framework. Emotion offers a convenient helper function called css, which generates a string - a class name that can be used as a value for the className property or any other relevant prop ...

Ways to delete a div element according to its associated value

Check out this code snippet on jsFiddle: http://jsfiddle.net/fH3Sc/ If you want to remove the last occurrence of each special-text div without changing the provided HTML, you can use the following jQuery code: $(".special-text").slice(0, -1).remove(); T ...

How can you quickly navigate to the top of the page before clicking on a link in the same window/tab?

Could someone assist me with a coding issue I am facing? I would like to be able to go to the top of the page when clicking on a link and have the link open in the same tab. I attempted to implement this functionality using the following code, however, I ...

In Firefox, certain scroll positions cause elements to vanish

I've been struggling with a peculiar bug that I can't seem to fix. The issue arises in Firefox when scrolling on a MacBook Pro 2019 15" at 1680x1050 resolution - product elements (not just images) begin to flicker. I have recorded a video of th ...

The Node module's package.json does not have a main "exports" defined

After recently adding the zx NPM package to my project, I encountered a puzzling issue. The installation went smoothly, and I proceeded to import it into my code: import { $ } from 'zx' (async () => { await $`mkdir test` })() However, u ...

What is the best way to retrieve the data from a specific section when a checkbox is selected in Angular 2?

When I select a checkbox for any section and then click the submit button, I want to display the details of that section in the console. Can someone assist me with this? **Stackblitz link:** : https://stackblitz.com/edit/angular-q7y8k1?file=src%2Fapp%2Fa ...

Formulation, on the other side of the comma

I have a calculation script that is almost working perfectly, but it seems to be ignoring values with decimal points. Can anyone offer some guidance on how to fix this issue? var selects = $('select'); var inputs = $('input'); selects. ...