Utilize JavaScript to save user-selected CSS styles by setting a cookie in jQuery

I am currently using a jQuery styleswitcher to change the stylesheet upon click. Despite trying various solutions, I have been unable to find a resolution to this issue. Could someone please assist me in setting a cookie for this functionality?

Markup:

    <ul class="colors-list">
        <li><a title="Black" id="black" class="black" ></a></li>
        <li><a title="Green" id="green" class="green" ></a></li>
        <li><a title="Blue" id="blue" class="blue" ></a></li>

    </ul>

jQuery

<pre><code>(function ($) {
"use strict";
var mainApp = {

    main_fun: function () {

        /*=====================================
         THEME SWITCHER SCRIPTS 
        ===================================*/

        //THE PANEL TOGGLE FUNCTIONALITY ON CLICK

        jQuery('#switch-panel').click(function () {
            if (jQuery(this).hasClass('show-panel')) {
                jQuery('.switcher').css({ 'left': '-50px' });
                jQuery('#switch-panel').removeClass('show-panel');
                jQuery('#switch-panel').addClass('hide-panel');
            } else if (jQuery(this).hasClass('hide-panel')) {
                jQuery('.switcher').css({ 'left': 0 });
                jQuery('#switch-panel').removeClass('hide-panel');
                jQuery('#switch-panel').addClass('show-panel');
            }
        });

        $('#black').click(function () {
            $('#mainCSS').attr('href', 'assets/css/style.css');  //PATH TO BLACK STYLESHEET
        });
        $('#blue').click(function () {
            $('#mainCSS').attr('href', 'assets/css/blue.css');  //PATH TO BLUE STYLESHEET
        }); 
        $('#green').click(function () {
            $('#mainCSS').attr('href', 'assets/css/green.css');   //PATH TO GREEN STYLESHEET
        });
        $('#red').click(function () {
            $('#mainCSS').attr('href', 'assets/css/red.css');    //PATH TO RED STYLESHEET
        });



    },

    initialization: function () {
        mainApp.main_fun();

    }

}


$(document).ready(function () {
    mainApp.main_fun();
});

}(jQuery));

Answer №1

Looking at this discussion - How can I manage cookie values?, there is some ready-made JS code for handling cookies.

In your scenario, you can update the cookie value within your jQuery .click functions.

Additionally, you should have code that executes when the document loads to check if a cookie is present on the user's browser. If it is found, you need to adjust the stylesheet according to the cookie value.

I've prepared an example for you based on your provided code. Feel free to customize it as needed. http://jsfiddle.net/biz79/pdjmc0n3/1/

JavaScript:

Creating/setting cookie with 24-hour expiration

    $('#black').click(function () {
      // add stylesheet code here...
      createCookie('cookie','black',1);
    });
    $('#blue').click(function () {
      // add stylesheet code here...
      createCookie('cookie','blue',1);
    }); 
    //...

If a cookie exists:

    $(document).ready(function(){
      updateResult();
    });

    function updateResult() {
      var cookieValue = getCookie('cookie');
      if (cookieValue.length) {
        $('#mainCSS').attr('href', 'assets/css/' + cookieValue + '.css');
      }
    }

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

How can I adjust the column width in OfficeGen?

Currently, I am utilizing officeGen for the purpose of generating word documents. <sup> let table = [ [ { val: "TT", fontFamily: "Times New Roman", }, { val: "Ten hang", ...

Creating a fixed tooltip in Bootstrap 4

After finding a static tooltip demonstration on the Bootstrap website, I attempted to replicate it in my project by copying the generated HTML code. Unfortunately, it did not work as expected. Despite Bootstrap 4 being in development, the documentation cou ...

Issue with JQuery mobile: dynamically inserted popup fails to appear

Can you help me troubleshoot an issue with my function? It's supposed to take a text string and output the text surrounded by '¬¬¬' in a button with a pop-up menu attached. The button looks fine, but when clicked, the popup ul list doesn& ...

What is the reason behind Rxjs switchMap only emitting the final value from an of() observable source?

Here are two code snippets, one using map and the other using switchMap. The functionality of map is clear: of('foo', 'bar') .pipe(map((val) => sanitizer(val))) .subscribe((val) => console.log('value:', val)); func ...

Add the item and increase its value within an array using AngularJS

http://plnkr.co/edit/NDTgTaTO1xT7bLS1FALN?p=preview <button ng-click="addRow()">add row</button> <div ng-repeat="row in rows"> <input type="text" placeholder="name"><input type="tel" placeholder="tel"> </div> I am cur ...

Replicate the styling of CSS class A and apply it to class B

Let's take a look at some code: <button id="test" class="ui-state-hover" value="Button"> In Context: I'm utilizing the JQuery UI CSS class ui-state-hover on an HTML button to ensure it always appears as if it's being hovered over. H ...

Is there a way to retrieve the widths of several <span> elements at once?

Having a few <span> elements generated dynamically, I need to find out their combined width. Wrapping them in a <div> and using alert($("#spanWrap").width()); resulted in the container's width instead of that of the <span> elements. ...

Issue with the visibility of nested dropdown list on the website

I am encountering an issue with a web page I am working on. On the menu bar, there is a button that triggers a dropdown list of components. These components have submenu items as well. Unfortunately, I am struggling to properly display this structure. I ne ...

I need assistance in obtaining the hashed password

I am attempting to retrieve the hashed password for the admin user. Despite my efforts to hash the password, I am encountering difficulties when trying to insert it into the user object. import encryptor from '../helpers/password'; let hashed_ ...

Generating model objects from JSON using Node.js

While it's common knowledge that any JSON can be easily converted into a JavaScript object, I'm facing a challenge with the GitHub API. I need to retrieve the profiles of several developers and enhance those objects with custom methods to process ...

:active state not functioning correctly

I've utilized the :after and :before pseudo-elements to create a border effect when hovering over the navigation links. I've been trying to achieve the same border effect in the :active pseudo-class as well. Can someone please guide me on how to ...

Encountering problem with selecting values in Select2 with ajax

I have implemented the Select2 plugin in my code as shown below: JavaScript function initAssignmentsAjax() { $("#assignments").empty(); $( "#assignments" ).select2( { placeholder: "Select an assignment", allowCle ...

The issue of not being able to add data to the client is encountered in a local setup involving Socket.io, MSSQL

I have a large dataset that needs to be retrieved from a SQL server using Node.js and then broadcasted to clients in real-time using Socket.IO. I've been successful in fetching the data, but the UI on the client side isn't updating. Although I c ...

Concerns with textbox placement while scrolling with an absolute position style

I have an ASP:textbox on a page with various controls and divs, where I am setting the style to position:absolute on the "onkeyup" event. The height of the textbox increases dynamically based on the characters entered, but the issue is that the textbox alw ...

Wait to send GET requests until all POST methods have finished, not just started

I'm currently facing two issues with my jQuery record-inserting process and I'm looking for help from the fantastic SO community to tackle at least one of them. Here are the issues: Problem 1 - Random server delays The first problem concerns th ...

Refresh the view when the URL is modified

Utilizing angularjs alongside ui-router (using the helper stateHelperProvider) to organize views and controllers on the page. Encountering an issue where the views are not updating as expected. The relevant code snippet config.js app.config(function($h ...

What is the best location to manage errors within a sequelize ORM query?

I am working with the Sequelize ORM within a Node/Express environment. My database has two tables: one for Users and another for Items. The Item table includes a foreign key that is linked to the UserId in the User table. Whenever I attempt to create an ...

Using `left: initial` does not function properly in Internet Explorer

Unfortunately, the tooltip does not display correctly in IE as desired. This is how it should look (in Chrome): https://i.sstatic.net/dCM9z.png However, this is how it appears incorrectly in IE: https://i.sstatic.net/Tq6rY.png Here is my CSS code for ...

I attempted to separate a string containing <br> tags using the explode function, but the method was not successful

In my code, there is a string that looks like this <br> ACCEPT:YES <br> SMMD:tv240245ce <br> This string is stored in a variable called $_session['result'] My task is to extract the following information either as an array or ...

How can I adjust the size of the renderer in Three.js to fit the screen?

Encountering issues with the code snippet below: //WebGL renderer renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); //TODO: set optimal size document.body.appendChild(renderer ...