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

Incorporate a new CSS class into a DIV using JavaScript

Sample HTML: <div id="bar" class="style_one"></div> Is there a way to include the class style_two without deleting style_one? final outcome: <div id="bar" class="style_one style_two"></div> ...

Shorten certain text in Vuetify

Here's an example of a basic select component in Vuetify: <v-select :items="selectablePlaces" :label="$t('placeLabel')" v-model="placeId" required ></v-select> I'm looking to apply a specific style to all selec ...

Tips for positioning the popup ul in relation to its parent li

How can the pop-up ul be positioned in the center of the parent li using CSS? * { margin: 0; padding: 0; } #track-nav { margin-left: 50px; margin-top: 50px; float: left; width: 100%; list-style: none; font-weight: bold; margin-bottom: ...

What is the best method to detect a change in scroll position on a webpage using JavaScript?

Is there a way to trigger an event when the page's scroll position changes? I'm interested in creating a dynamic table of contents similar to (where the active item changes as you scroll). Can this be achieved without directly accessing the cu ...

Having trouble with clicking on an icon link within a list

Seeking assistance with creating a social media icon/link list for the first time on this platform. Any help is appreciated! <div class="social-links"> <ul> <li class="m-link"> <a href="&q ...

Error: The jQuery TableSorter Plugin is unable to access property '1' as it is undefined

I've been attempting to utilize the jquery table sorter plugin, but I keep encountering an error when trying to sort the table. The error message I'm receiving is: cannot read property '1' of undefined This is the HTML code I have: ...

Upon page refresh, products are automatically added to the cart

While developing a shopping cart code, I encountered an issue where refreshing the page automatically added a product to my cart without any action from me. For instance, my website displays three products: Apple, Banana, Orange. When I click on Apple, it ...

In React, when utilizing the grid system, is there a way to easily align items to the center within a 5 by

I need to center align items within the material-UI grid, with the alignment depending on the number of items. For instance, if there are 5 items, 3 items should be aligned side by side in the center and the remaining 2 items should also be centered. Pleas ...

No response text returned from the local Ajax request

Currently, I am facing a challenge while attempting to send an ajax call from the client to my server containing data related to an input parameter. The issue is that although I can view the data in my server's console, it does not display in the brow ...

A new module is unable to load Angular Material

Recently, I developed an Angular material module similar to a core module. import { NgModule} from '@angular import {MatCheckboxModule} from '@angular/material/checkbox'; @NgModule({ imports: [ MatCheckboxModule ], exports: [ ...

Utilizing CSS naming conventions to bring order to class inheritance

I'm a bit unclear about the rationale behind using this specific CSS structure: h2.class-name It seems like you could simply use .class-name and apply that class to the h2 element: <h2 class="class-name">Title thing</h2> Unless it&apos ...

Selecting an entire row in a Kendo grid

Is there a way to configure kendoGrid to highlight the entire row when clicked on? I have tried setting: scrollable: { virtual: true } and disabled paging, but it doesn't seem to work as intended. You can view an example here: Kendo UI Dojo When ...

Tips for creating row grouping in React JS

Currently, I am working on a React application and I would like to incorporate grouping similar to what is shown in the image. I have looked into row grouping but it doesn't seem to be exactly what I need. How can I go about implementing this feature? ...

Tips for waiting for a Promise to resolve before returning a new Promise

In the process of developing a web application tailored for crafting retail signage, I have integrated Firestore to manage pertinent information about these signs. One specific functionality I am working on is enabling users to effortlessly remove all exis ...

I am attempting to link my Firebase real-time database with Cloud Firestore, but I am encountering import errors in the process

I am currently working on enhancing the online functionality of my chat app by implementing a presence system using Firebase Realtime Database. Here is the code snippet that I have created for this purpose: db refers to Firestore and dbt refers to the Rea ...

Is there a way to make the submit button navigate to the next tab, updating both the URL and the tab's content as well?

I am encountering an issue with my tabs for Step1 and Step2. After pressing the submit button in Step1, the URL updates but the component remains on tab1. How can I resolve this so that the user is directed to the Step2 tab once they click the submit butto ...

Shifting and positioning the card to the center in a React application

I am currently constructing a React page to display prices. To achieve this, I have created a Card element where all the data will be placed and reused. Here is how it appears at the moment: https://i.stack.imgur.com/iOroS.png Please disregard the red b ...

What is the best way to pass the value from one textfield to another using material UI in a react application?

I'm looking to transfer the content from a text field in a dialog window to another text field that is not embedded. However, instead of transferring the actual text field value, I'm getting an output of "object Object". Can you help me figure ou ...

"Implementing a method to update an object by its Id within a nested array that includes children, and then managing the state in

How can I dynamically toggle the isExpanded property on click based on an element's ID in a React project? Below is the JSON data structure I am working with const handleExpandOutlineItem = (id: string) => {} This is the structure of my JSON data: ...

Issues with displaying or hiding a DIV using javascript - popup box unresponsive

I am working with this ASPX code: <div id="IsAccountingOk" class="modalDialog"> <div> <a href="#close" title="Close" class="close">X</a><br /> <asp:Label ID="lblIsAccountingOkHeader" runat="server" Text ...