Prevent CSS from resetting on page refresh

I am experiencing an issue with my HTML page that has two CSS files - one for a light theme and one for a dark theme. Whenever I click the corresponding button, the theme changes to either light.css or dark.css.

The problem is that whenever I refresh the page, reload it, or go back, the theme always reverts back to the default CSS (which is the light.css file).

Is there a solution to make sure that when I click the button and refresh the page, it stays on the dark.css theme?

Thank you.

Answer №1

To customize the theme and store the user's preference, you can utilize cookies, localStorage, or sessionStorage. These methods allow you to save both the default theme and the selected one. Upon page load, retrieve this information from the chosen storage mechanism and apply the desired theme accordingly.

For example, during page loading:

let storedTheme = localStorage.getItem('theme');
if(!storedTheme){
    storedTheme = 'light';
    localStorage.setItem('theme', 'light');
}
// Use the storedTheme variable to display the light theme

And in the event of a theme change by the user:

localStorage.setItem('theme', 'dark');
storedTheme = 'dark';

Answer №2

If you prefer not to rely on back-end methods for replacing the style.css file, an alternative is to utilize local storage in the following manner:

$(function(){

  setSiteTheme(getSiteTheme());
  
  function setSiteTheme(themeName) {
    //Uncomment this in your app: window.localStorage.setItem('themeName', themeName);
    $('link[data-theme]').attr('href', themeName);
  }
  
  function getSiteTheme() {
    //Uncomment this in your app: return window.localStorage.getItem('themeName') || 'light.css';
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<link rel="stylesheet" href="/css/styles.css?version=5a6992221f52c" data-theme>

Remember to then add the DATA-THEME attribute to the link tag within the head section of your document. Also, ensure to uncomment the necessary lines as indicated.

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

The media file located at http://url/file.mp3 was unable to be decoded

Recently, I set up a website on our local area network. Previously, the online version worked perfectly fine. However, after installing it on the LAN, I encountered an issue with the audio not working at all. Upon inspecting through Firefox's develope ...

Extracting live content from a website within a native Webview

Running an eCommerce website along with a simple mobile app for both iOS and Android that features a basic tab bar menu, including icons like a shopping cart, profile, refresh button, etc., as well as a Webview to display the website content. The App' ...

Utilizing Smoke.js within a PHP environment

I created a PHP function to validate HTML form fields. When an error occurs, the code below will display an error message using JavaScript "alert": echo '<script type= "text/javascript">alert("account not found in database")</script>&apo ...

Utilizing SQL injection vulnerabilities in MSSQL databases through a Node.js

In my Node.js Backend, I'm working on preventing SQL Injection. While using the mssql package for testing purposes, I discovered that if a parameter contains the character ', the query fails to work (as expected). sql.connect(sqlConfig, function ...

Transferring information from one website to another

I need to transfer content from one website to another while maintaining good SEO practices. Using Iframes is not an option, and PHP won't work in the CMS I'm using. I attempted a different approach: $('#target-div').load('http:/ ...

Ways to Extract Every Single Line

Usually, my go-to is beautifulsoup for line by line parsing. However, in this particular scenario, it seems to be printing blanks instead. My goal is to extract the link and title of each job posting. from bs4 import BeautifulSoup import requests import ...

The Vue router fails to navigate to the designated destination

Having an issue with vue-router where routing doesn't work properly when trying to navigate to a child route. { path: '/user', name: 'User', component: User, children: [ { path: 'profile', ...

Looking to subtly transition from the current webpage to the next one with a fading effect?

I'm looking to create a smooth transition between web pages on my site by slowly fading out the current page and fading in the next one when a link is clicked. $(document).ready(function() { $('body').css("display","none"); $(&a ...

Functionality problem with adjusting font size in jQuery date picker

Recently, I integrated jQuery and datapicker features into my ASP .NET MVC 3 (Razor) project and noticed that the font size of the datapicker is exorbitantly large. Does anyone have any suggestions on how to adjust this issue? Your help would be greatly ...

What is the best way to render CSS files in express.js?

My file organization looks like this: node_modules structures {HTML Files} styles {CSS Files} app.js package-lock.json package.json I have already imported the following: const express = require('express'); const app = express(); const p ...

Strategies for implementing classes in Typescript

I've been working on incorporating more classes into my project, and I recently created an interface and class for a model: export interface IIndexClient { id?: number; name?: string; user_id?: number; location_id?: number; mindbody_id?: nu ...

Using an npm package: A step-by-step guide

Recently, I added the following package to my project: https://www.npmjs.com/package/selection-popup I'm curious about how to utilize its features. Can you provide some guidance on using it? ...

Arranging div elements into columns side by side with Flexbox

I've been working on the frontend of my chat web app and recently discovered flexbox. I'm struggling to center two elements with a blue background below the "CHAT" heading, aligned with two green elements like a black square. My challenge lies in ...

The marriage of a sticky and floating navigation bar using the power of Bootstrap 4

I am currently designing a navigation bar inspired by the layout on the EA GAMES website. While it functions perfectly in Chrome, I am encountering significant display issues in Internet Explorer. Any suggestions on how to troubleshoot and resolve this pro ...

What is the best way to assign a Python variable to an <a-assets> element?

There exists a Python function that provides the chosen background <a-sky ID="sky" color="{{object.background}}"></a-sky> The backgrounds can be in the format of '#c6aa99', '#e1a600', '#290942', 'star' ...

Alignment in HTML / CSS / ReactJS: Leveraging the Text-align attribute

My attempt to align the text to the right within my div element has been unsuccessful. Despite using text-align: right and width: 100%, the issue persists. It seems that the problem lies within the left-side and right-side attributes, but I am unable to pi ...

Creating a unique pattern in HTML5 to properly format phone numbers

<input type="text" pattern=" "> Is there a way to format this pattern to meet the following requirements? Guidelines: The first number must always be zero Only numbers and spaces are allowed Exactly 11 or 12 characters are permitted (including sp ...

Creating Space in CSS between Two Widgets

Is there a way to align the managers tab under the checkers and stockers areas on this page? The current setup has the manager button overlapping with both of them. If anyone has any suggestions on how to address this issue, I'm all ears. Thank you! ...

Guide to creating draggable text on a video with HTML

I have a challenge where I need to overlay text on a video and make it draggable across the entire video. Currently, I am able to display the text over the video successfully, but when I try to drag it and then drop it, the text appears below the video and ...

Using jQuery or JavaScript to delay execution until the image width has been adjusted

I'm encountering a timing issue with the loading functions on my page. The problem arises when I need to retrieve the width of an image after two specific events have occurred: 1) The image has finished loading 2) The image's width has been adj ...