Ensure the dark mode switch CSS remains consistent when navigating to different pages

I have been working on a code to toggle between dark and light mode on a webpage. While it works fine within the current page, the issue arises when I navigate to another page or refresh the current one - the mode resets back to default (light). How can I make the webpage remember the mode I choose? Below is the simple code snippet I am using to switch between CSS styles.

TOGGLE BUTTON

<i class="fa fa-toggle-on fa-2x active" id="on" style="display:none;" onclick="darkswitchoff()"></i>
<i class="fa fa-toggle-on fa-2x fa-rotate-180 inactive" id="off" onclick="darkswitchoon()"></i>

SCRIPT

<script>
$(document).ready(function(){
    $('.middle').click(function() {
        $('.inactive, .active').toggle();
  });
});
</script>

<script>
function darkswitchoff() {
    document.getElementById('mainstylesheet').href='/assets/css/main.css';
}

function darkswitchoon() {
    document.getElementById('mainstylesheet').href='/assets/css/main-dark.css';
}
</script>

Answer №1

In order to maintain the state throughout your application, one simple approach is to make use of cookies instead of relying on additional libraries.

<script>
document.cookie = "isDark=true";
</script>

By storing a value in a cookie, you can easily retrieve it later to enable dark mode. Just remember that cookies store data as strings. For example, if you only want to track whether the user prefers dark mode:

<script>
if(document.cookie){
//Code to Enable Dark Mode
}
</script>

Alternatively, a more robust solution would be to implement a library such as Redux, which offers a sophisticated "store" for managing various types of app data.

Answer №2

To ensure the dark mode stylesheet is loaded, it's recommended to store this setting in either a Cookie or localStorage. If the Cookie is already set or the setting is found in localStorage, the dark mode stylesheet will be automatically loaded.

Answer №3

Unfortunately, the code provided here will not work properly. However, you can access the working version through this dark-mode link.

const toggleSwitch = document.querySelector(
  '.theme-switch input[type="checkbox"]'
);
const currentTheme = localStorage.getItem("theme");

if (currentTheme) {
  document.documentElement.setAttribute("data-theme", currentTheme);

  if (currentTheme === "dark") {
    toggleSwitch.checked = true;
  }
}

function switchTheme(event) {
  if (event.target.checked) {
    document.documentElement.setAttribute("data-theme", "dark");
    localStorage.setItem("theme", "dark");
  } else {
    document.documentElement.setAttribute("data-theme", "light");
    localStorage.setItem("theme", "light");
  }
}

toggleSwitch.addEventListener("change", switchTheme, false);
@import url("https://fonts.googleapis.com/css?family=Lato:400,400italic,700|Sansita+One");
/** CSS styles **/
<div class="theme-switch-wrapper">
  <label class="theme-switch" for="checkbox">
    <input type="checkbox" id="checkbox" />
    <div class="slider round"></div>
  </label>
</div>

<section>
  /** Article content **/
</section>

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 with Dismiss Button Display in Bootstrap Alert

I've been experimenting with Bootstrap and I realized that even though I followed all the instructions on their Alert page, my close button just appears as a large grey square with an X in it. Any suggestions on what might be missing? https://codepe ...

How to send arguments to a callback function in Next.JS

Here's the code snippet I'm working with: import Router from "next/router"; import React from "react"; export default function MainIndex() { return (<React.Fragment> <h1>Main Index Page</h1> ...

The issue I'm facing is that the ng-click functionality in Angular JS is not functioning properly when the

Upon loading the page, my JavaScript function creates a tree structure from JSON data and generates a list of anchor tags which look like this: <a ng-click="shareParent(4619)">Some data</a> Despite associating the ng-click directive with the ...

Setting React's PUBLIC_URL dynamically at runtime can be accomplished by manipulating the process.env.PUBLIC

I'm currently working on a new CRA project that will be utilized on a website hosting multiple plugins within an "iframe". These plugins are served using a proxy, and the plugin URLs are unknown until they are instantiated. To retrieve the location o ...

Scope variable changes are not being acknowledged by the directive

Here is a directive I am working with: <span ng-show="{{ save_state == 'saved' }}"> Saved </span> <span ng-show="{{ save_state == 'saving' }}"> Saving </span> <span ng-show="{{ save_state == 'error ...

`I'm experiencing issues with my AJAX call when using Django`

As part of my blog practice, I'm trying to ensure that all notifications are marked as seen when a user views them. This functionality works fine when I manually go to the URL, but it's not working when using Ajax. Here is the JavaScript code: ...

Moving labels to the left side of the nodes in a Sankey diagram

Below is the Sankey diagram code used in their 'Definition' section. You can also access the code by clicking on the CODE button located on the right side of the diagram. I'm wondering how we can make the countries on the left (such as Afri ...

Send variable to jQuery from a div element

I'm struggling with adjusting the height and width of a dialog box using a jquery function. I want to pass a parameter from within the DIV, but I haven't been successful in finding a solution. Any suggestions would be greatly appreciated. $.fx.s ...

Instructions for instructing Codeception to finalize the selection from a dropdown list without the need to click on a submit button

I am facing an issue where I am able to select an element from a drop down list in codeception, but it is not being displayed as selected in the box. I believe the select operation is not completing properly. Since there is no submit button available, I at ...

Trouble with webpage design persists following recent modifications

Today, I decided to make some alterations on the header.php file of my WordPress website in order to tweak the flag icons displayed at the top of the page. However, when I refreshed the page, everything looked completely chaotic. Even after undoing all th ...

I am looking to configure a specific MUI dropdown to appear below a particular field

In my scenario, when I click on the select dropdown and a popup appears above the field, I would like it to open below that specific area. The desired behavior can be observed in the code sandbox link provided. I need to configure it to start from below th ...

Exploring the World of ASP MVC and Jquery ajax Search

Recently, I created a code for an ajax search function that retrieves user information. In the Controller section: public JsonResult SearchPeopleByName1(string keyword) { System.Threading.Thread.Sleep(2000); ApplicationDbContext myDbConte ...

The issue at hand is that certain Views within Dot net are unable to reach the CSS and JavaScript files

A issue has arisen where certain views (but not all) are unable to access certain css and js files, resulting in a "404 Not Found" error. For instance, the View of .../Details/Index/1 cannot access one css file and one js file (despite being able to acce ...

No data is being retrieved by SWR

I'm struggling to make SWR work in my code. Despite trying multiple examples, I can't seem to get it functioning properly. It's frustrating because the code looks fine and should work. I feel like I must be missing something simple. Current ...

Implement a feature in JS/HTML where clicking on a button shifts a specific section of a row from one table to another while simultaneously deleting the remaining

I am facing an issue with two tables - addFriends and existingFriends. The addFriends table contains a button in the fourth column, which, upon clicking, should delete the corresponding row from that table and add it to the existingFriends table. Currentl ...

Encountered an error: Trying to access 'location' property from undefined in express app

Encountered Issue : I am facing an error that is hindering me from fetching data from the HTML form. Every time I input values into the form and click the button to send the data to an API for saving it in the database, this error pops up: Cannot read pro ...

How to perfectly center a text box in HTML

UPDATE: I have included the relevant JavaScript code. Essentially, a text box appears when a checkbox is clicked, but I want the text box to be centered on the page. I am attempting to center align a text box on the page, but I am struggling to achieve th ...

Tips for safeguarding AJAX or javascript-based web applications

Utilizing AJAX, this function retrieves information about an image in the database with the ID of 219 when a button is clicked. Any visitor to this webpage has the ability to alter the JavaScript code by inspecting the source code. By modifying the code a ...

I am facing difficulties when trying to map the data using react js/axios

After removing the map function from the code, I encountered an error stating that map is not a function. Can someone please assist me with this issue? Here is the updated code: const [text, setText] = useState([]); const axios = require('axios&ap ...

Automatically setting the checkbox for each unique ID based on database values for the specified hobby

Query: The issue I am facing is that when I click the edit button for the first time, the checkboxes get checked based on the values in the database table. However, when I click another edit button for the second time, the checkboxes do not get unchecked f ...