Strange CSS/browser storage glitch

UPDATE: JUST REALIZED THIS ISSUE IS ONLY OCCURRING ON FIREFOX, NOT CHROME

ANOTHER UPDATE: Oddly enough, this problem only occurs locally. When I push it to GitHub, everything works fine. So strange. I suppose that means it's not a major issue.

On my portfolio website, users can choose from three different "skins" in the navbar dropdown menu (None, Christmas, and Easter). This functionality is achieved using a JavaScript script to change the stylesheet attribute. Here's how it's implemented:

function checkSkin() {
    var skin = localStorage.getItem("skin");
    if (skin == null) {
        skin = "default";
    }
    $("link[type='text/css']").attr('href', "style/" + skin + '.css');
    $('select option[value="' + skin + '"]').attr("selected", true);
}

function applySkin() {
    console.log(event.target.value);

    localStorage.setItem("skin", event.target.value);

    checkSkin();
}

When a user switches skins, the local storage retains the chosen skin for subsequent visits. Therefore, if you select "Easter" once, it will remain as "Easter" during future visits.

Each stylesheet primarily alters color schemes, with most of the content remaining consistent across them. Updating styles becomes cumbersome as I have to update all three stylesheets frequently.

I came up with an idea – what if I include two stylesheets in the head tag? One on top, and one below. The script would then change the one below. The revised script now looks like this:

function checkSkin() {
    var skin = localStorage.getItem("skin");
    if (skin == null) {
        skin = "default";
    }
    $(".subStyle").attr('href', "style/" + skin + '.css');
    $('select option[value="' + skin + '"]').attr("selected", true);
}

function applySkin() {
    console.log(event.target.value);

    localStorage.setItem("skin", event.target.value);

    checkSkin();
}

This modification works well, but now the selected skin doesn't persist across pages as before. Each section of the portfolio remembers its own skin selection. For instance, "About Me" might be set to Christmas while Contact remains unchanged unless manually updated.

What could be causing this behavior?

UPDATE:

Here's an excerpt from the HTML at the top of one of my pages to provide better insight into how this setup functions:

<!DOCTYPE html>
<html lang ="en-us">
<head>
  <meta charset="UTF-8">
  <title>Downloads</title>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

   <link rel ="stylesheet" type="text/css" href="style/main.css">
  <link rel="stylesheet" class="subStyle" type="text/css" href="style/default.css">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <script src="portfolio.js"></script>



 </head>

 <body onload="showStuff(), checkSkin()">

Here's where the skin is selected:

 <span class="skin" style="float:right;">Change Skin? <select onChange="applySkin(event);">
        <option value="default">None</option>
        <option value="easter">Easter</option>
        <option value="christmas">Christmas</option></select> 
    </span>

Answer №1

I created a quick and not-so-pretty replica on CodePen to investigate the problem. Although I haven't shared the entirety of your code here, the only way I could reproduce your issue was by excluding the invocation of skinCheck() during page load.

My assumption is that, for some reason, this function isn't executing with each page load. To confirm this, you can simply add a console.log statement at the beginning of the function. For instance:

function skinCheck() {
    var skin = localStorage.getItem("skin") || 'default';

    $(".subStyle").attr('href', "style/" + skin + '.css');
    $('select option[value="' + skin + '"]').attr("selected", true);

    console.log('Setting page style (post jquery load)');
}

skinCheck();

Replica: https://codesandbox.io/s/crazy-ioana-b0n16z?file=/index.html

A key point to consider is that the page may exhibit slight jitteriness upon loading due to the loading time of jQuery and your theme's CSS. One approach to mitigate this within this setup is to implement a loading state that appears opaque initially and then fades away once the theme is fully loaded.

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 Angular filter is waiting for the ng-repeat to be populated

I have a filtering system that includes dropdown options to filter the displayed content. The content is fetched from a database and takes a few milliseconds to display. During this time, I encounter several errors related to the filtering system. Does any ...

Troubleshooting an Issue with CSS Sliding Doors

I'm having trouble getting the right image to show on my website. The left side of the image is fine, but I can't figure out how to make the right one appear. As a HTML/CSS beginner, I'm still learning the basics. For more information, vis ...

Steps for referencing an autogenerated id in a Firestore collection

I need assistance updating a 'progress' field in a document with an autogenerated ID (using Firestore) every time the progress button is clicked. https://i.stack.imgur.com/hZieN.png Despite my attempts, nothing seems to work. Here is the method ...

Using the spread operator to pass properties in React

Update: After delving deep into the documentation, @wawka has discovered that there may be some issues with the react-router-dom v^5.0.1 causing problems with the myLink2 component. It seems like a rewrite of this component may be necessary. In my React p ...

Obtain a range of dates within a specified timeframe by utilizing JavaScript

Is there a way in JavaScript to retrieve a list of days between two dates in MySQL format without using any libraries? Here is an example of how it can be done: function generateDateList(from, to) { var getDate = function(date) { //MySQL Format ...

Ways to expand the width of mat-dialog-actions component in Angular 8

Is there a way to make the cancel and save buttons in the dialog window take up the entire available space? If anyone has any suggestions on how to achieve this, please let me know! ...

Using Ajax with Controller Action in Yii2

As a newcomer to programming, I am facing an issue where I need to call a function when the user inputs data and clicks the submit button. Although I am working with Yii2, I lack experience in Ajax. Despite my efforts, the controller action is not being tr ...

Nightwatch is a tool that allows you to interact with elements on a webpage by clicking on an element within

I have a scenario on my website where I have two separate div elements: <div class="wg-block" data-reactid="10" <div class="wg-header" data-reactid="11"/div> .... <h4 class='condition'> "Text" </h4> <div cl ...

The subsequent code still running even with the implementation of async/await

I'm currently facing an issue with a function that needs to resolve a promise before moving on to the next lines of code. Here is what I expect: START promise resolved line1 line2 line3 etc ... However, the problem I'm encountering is that all t ...

Hover to stop menu movement

Can someone help me achieve a similar menu hover effect like this one? I'm trying to create a menu with a hold/pause effect on hover, specifically in the section titled "A programme for every vision". The goal is to navigate through the sub menus smo ...

The source 'http://localhost:3000' is not authorized to access the Twitter API

I am working on a web application that utilizes the Twitter API REST. On one of my pages, I have a list of Twitter accounts and a button to add a new account. When this button is clicked, it triggers a function in the Angular controller: // Function to ...

The addEventListener function seems to be malfunctioning in the React JS component

Initially, the program runs correctly. However, after pressing the sum or minus button, the function fails to execute. componentDidMount() { if(CONST.INTRO) { this.showIntro(); // display popup with next and previous buttons let plus = docume ...

Keystrokes malfunctioning on Firefox while functioning correctly on Chrome

I am currently in the process of developing a web scraping application using Python and Selenium to automate tasks on a server. Specifically, I am looking to create and schedule posts through CreatorStudio for sharing on Instagram. However, I have encounte ...

I want to display events from my database table on their corresponding dates using JavaScript and jQuery. How can I achieve this?

Using the FullCalendar plugin, I attempted to achieve a specific functionality, but unfortunately fell short of my goal. Below is the snippet of my scripting code: $('#calendar').fullCalendar({ //theme: true, header: { ...

Customizing the Class of a jQuery UI ui-autocomplete Combobox Container

Is there a way to customize the ui-autocomplete div by adding a custom class? I have several autocomplete widgets on my webpage, and I need to style their drop-downs differently. Since editing the ui-autocomplete class directly is not an option, I am wor ...

Creating a personalized design for Bootstrap Badge

Looking to customize the shape of bootstrap badges from the default ellipse to a rectangle with rounded corners. Any tips on the best approach to accomplish this? ...

What is the best way to use an object as a key to filter an array of objects in JavaScript?

My data consists of an array of objects: let allData = [ {title:"Adams",age:24,gender:"male"}, {title:"Baker",age:24,gender:"female"}, {title:"Clark",age:23,gender:"male"}, {title:"Da ...

What could be the reason why the navbar ul li a instance is not appearing in Bootstrap 4 modal when using an

Can anyone help me solve the issue I'm having with viewing HTML in a Bootstrap 4 modal? Everything shows up except for the navbar ul li a elements. I've searched for a solution everywhere, but haven't found one yet. Please assist! (I want t ...

Using JQuery's .mouseover and .mouseout methods to modify font colors on a webpage

Hi there, I'm new to JQuery and trying to experiment with some basic functionalities. I have a simple navigation menu created using an unordered list, and I want to change the font color of the currently hovered list item using JQuery. However, I&apos ...

javascript - Include new parameter in object literal and retrieve

I have a base object that I define using an object literal: var obj = { key1 : 'value1', key2 : 'value2' } Now, I want to pass this object to a function and extend it like this: myFunction( obj + { key3 : 'value3' ...