Save a CSS class within the browser

One feature of my project is the ability to change the site theme with a simple click:

<ul>
  <li class="=contact"><a href="#">Contact</a></li>
  <li class="facebook"><a href="#">Facebook</a></li>
  <li class="twitter"><a href="#">Twitter</a></li>
  <li class="rss"><a href="#">Feed Rss</a></li>
  <li class="change-theme"><a href="#">Change Theme</a></li>
</ul>

Clicking on the link within the <li class="change-theme"> triggers the following script:

$('.change-theme').click(function () {
  $('body').toggleClass('theme-dark');
});

This adds the class theme-dark, thereby changing the site theme. However, upon page refresh, the default theme reverts back. Is there a way to save the chosen theme and maintain it even after browser updates?

Answer №1

Utilizing local storage allows for data to be stored indefinitely without an expiration date:

$('.change-theme').click(function () {
    $('body').toggleClass('theme-dark');
    if($('body').hasClass('theme-dark')){
        localStorage.setItem('theme', 'theme-dark');
    }
});

$(document).ready(function(){
    var theme = localStorage.getItem('theme');  
    if(theme !== ''){      
        $('body').addClass(theme);
    }
});

On the other hand, sessionStorage stores data only for a single session until the browser is closed (usage is similar to localStorage).

This feature is supported by all major browsers, with Internet Explorer implementing it since version 8.

Note: Only strings can be stored in web storage.

If you prefer using cookies instead, you can do so by:

document.cookie="theme=theme-dark"; //setter

and

var x = document.cookie; //getter

Reference

webStorage

cookies

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

What is the best way to prompt a jQuery plugin to update the information it has retrieved?

I'm currently working on implementing jQuery Pagination along with a popup form. My question is, after saving data in the form, how can I refresh the Pagination plugin to only load the data for the current page without having to refresh the entire web ...

Filtering and pagination on the server side using AngularJS

Currently, I am dealing with several input fields. Let's take the example of an input field named "search". My goal is to filter the results of an object when someone types into that field; however, I prefer to perform this filtration on the server si ...

Applying a CSS class to a newly generated row with JavaScript

I have a JSP page where I dynamically add rows to a table using a different Javascript function than in my previous query. While I can add elements to the table columns, I'm unable to apply a style class that is defined in a CSS file. Here is my Java ...

The random sorting algorithm in the query_posts function is disrupting the formatting of the CSS

<?php query_posts($query_string . '&orderby=rand') ?> Hello everyone, I recently added the code snippet above to my portfolio page template.php. You can view it at However, I've noticed that sometimes the CSS breaks when you rel ...

Attempting to save data to a .txt file using PHP and making an AJAX POST request

I have been facing an issue while trying to save a dynamically created string based on user interaction in my web app. It's just a simple string without anything special. I am using ajax to send this string to the server, and although it reaches the f ...

Developing a Restful Put Request using JQuery

Having some trouble calling a restful service that was developed in ServiceStack. I've got the GET(s) calls working, but Put and Post are giving me issues. Here's my client-side script: function savePartner(e) { $.ajax({ ...

Strategies for redirecting a PDF download response from an API (using node/express) to a user interface (built with React)

I have a specific setup where the backend server generates a PDF, and when a certain endpoint is visited, it triggers the download of the PDF. However, due to security restrictions, I cannot access this endpoint directly from the frontend. To overcome this ...

Changing JSON DateTime into a readable format with the day, month, year, hour, minute, and am/pm

I am looking to change the datetime format from 2015-03-17T06:14:49.2295964Z to 17/03/2015 06:15 AM using either jquery or JavaScript. Could you provide some insight into this initial format? I have a controller method that sends datetime to an ajax cal ...

How to convert serialized jQuery form data into a multi-dimensional array?

I am trying to extract data from a form, convert it into JSON format, and then send it using AJAX. The desired JSON structure is as follows: { items: [ { id: 7, name: 'Book', price: 5.7 }, { id: 5, name: 'Pencil', price: 2.5 ...

Using Ajax to send a variable to PHP and then selecting data from an SQL database

Currently, I am facing an issue where I need to pass a variable to my "fetch" PHP file. In the fetch.php file, I execute a query to a MySQL database with certain parameters. However, I have hit a roadblock in the process. I am able to retrieve the variab ...

Using AngularJS: Trigger a directive method as a callback directly from the controller

I have a specific directive that utilizes a jQuery "multiselect" plugin to improve any select element with the attribute "filtermultiselect". The issue I am facing is that the select element is populated through an ajax call, and I do not want the directiv ...

Toggle the mute and unmute feature for a participant in an AWS Chime meeting

Hello everyone! I'm looking for details on the AWS Chime SDK (amazon-chime-sdk-js). Is it possible with the Amazon Chime SDK for 3 participants (Anna, John, and Lenny) in a meeting room to have Anna ignore Lenny's microphone and only hear John, ...

Tips for dynamically populating a dropdown menu in Laravel with Ajax and JQuery

Hey pals, I'm encountering an issue with Ajax. Everything seems to be running smoothly when the page initially loads. However, once I hit the add button to insert a new row for a second entry, things start to go haywire. The functionality is perfect u ...

The size of my React Native app is significantly larger than expected once installed

I recently developed a React Native app, and while the release APK size is only 28 MBs, I was shocked to see that the storage size is a whopping 62 MBs. I am desperately looking for a solution as I need to deliver this project soon. Please help me resolv ...

Creating messages from an array using vanilla JavaScript or jQuery

I have an array of objects containing messages that I want to display on my webpage, but I'm unsure how to approach it. [{"message":"dwd","user":"csac","date":"07.04.2021 20:46"}, {"mes ...

Issues with forms displaying as raw text within Laravel 5

I recently entered the realm of Laravel. While following a tutorial on OpenClassrooms, I encountered some challenges as the tutorial was for Laravel 4 and I am using Laravel 5. After struggling to adapt my controllers and resolve namespace dependency erro ...

Strategies for Effectively Managing Null Checks in Your JavaScript Project

When retrieving data from the BE API, it is in the format: { "details": { "address": { "street": "123/4", "city": "Banglore" } } } In our React project, we access this dat ...

Discovering the size and count of JavaScript objects within a browser's memory

Many suggest using the Chrome Profiler Heap Snapshot to analyze memory usage, but I have found that on an empty page (no JavaScript or CSS, just HTML), it shows a heap size of 8MB and anywhere from 12 to 30 thousand objects depending on its mood. This tool ...

What is the process for upgrading TypeScript to the latest version?

Is there a way to upgrade TypeScript version for ASP.net MV5 project in Visual Studio 2015? I attempted searching through Nuget but couldn't locate it. There seems to be an issue with the razor intellisense (index.d.ts file) and I'm hoping that ...

Can you explain the mechanism behind how the spread syntax (...) interacts with mapGetters?

When implementing a computed getter using the mapGetter helper from Vuex, the syntax typically involves using the spread operator in the following way: ...mapGetters([ 'getter1', 'getter2', 'etc' ]) Although th ...