Managing cookie-related changes to CSS classes using jQuery can present challenges

I stumbled upon an interesting solution for changing background color and storing it in a cookie by utilizing jquery.cookie. After making a few tweaks, it worked smoothly:

$(document).ready(function () {
 $("body").css("background-image",$.cookie("<?php echo $_SESSION['username_login']; ?>"));
     $("#background-change").change(function (event) {
       var img =  $(this).val();
        $("body").css("background-image",img);
         $.cookie("<?php echo $_SESSION['username_login']; ?>",img, {path: '/', secure: true});
     });
 });

Building on this, I attempted to create a theme color switcher with the default class of .w3-blue-grey. Here's what I came up with:

$(document).ready(function () {
$(".w3-blue-grey").toggleClass($.cookie("<?php echo $_SESSION['username_login']; ?>col"));
    $("#color-change").change(function (event) {
      var col =  $(this).val();
       $(".w3-blue-grey").toggleClass(col);
        $.cookie("<?php echo $_SESSION['username_login']; ?>col",col, {path: '/', secure: true});
    });
});

Although I tried to avoid naming conflicts by using different cookie names, this code doesn't seem to function as intended. I've encountered various issues – sometimes it changes colors incorrectly, refuses to revert to the default, or even renders the element transparent. I'm at a loss...

Switching to switchClass instead of toggle didn't yield favorable results either.

I suspect the problem may stem from the order of selection in the code. Sharing my HTML snippets for context:

<select name="wall" id="background-change" class="w3-padding">
   <option>...</option>
   <option value='url("img/wall6.png")'>Main</option>
   <option value='url("img/wall2.png")'>Option 1</option>
   <option value='url("img/wall3.png")'>Option 2</option> 
</select>

My background changer select works fine. Here's the snippet for my theme switcher:

<select name="color" id="color-change" class="w3-padding">
        <option >...</option>
        <option value='w3-blue-grey'>Light grey</option>
        <option value='w3-indigo'>Indigo</option>
        <option value='w3-blue'>Light blue</option>
</select>

After spending hours troubleshooting this issue, I'm open to any suggestions or alternative solutions. Your input is greatly appreciated.

Update: I managed to resolve the issue. Are there any better approaches you can recommend?

<script type="text/javascript">
       $(document).ready(function () {
        $(".w3-blue-grey").css('cssText',$.cookie("<?php echo $_SESSION['username_login']; ?>col"));
            $("#color-change").change(function (event) {
 var col =  $(this).val();
  $(".w3-blue-grey").css('cssText',col);
   $.cookie("<?php echo $_SESSION['username_login']; ?>col",col, {path: '/', secure: true});
            });
        });
</script>    

Answer №1

After resolving the issue with switching classes, I have opted to make adjustments to style the class instead. When styling the HTML select, ensure that the value is the full style you want to apply, and then pass it into the cssText property.

       $(document).ready(function () {
        $(".w3-blue-grey").css('cssText',$.cookie("<?php echo $_SESSION['username_login']; ?>col"));
            $("#color-change").change(function (event) {
 var col =  $(this).val();
  //window.alert(col);
  $(".w3-blue-grey").css('cssText',col);
   $.cookie("<?php echo $_SESSION['username_login']; ?>col",col, {path: '/', secure: true});
   //location.reload();
            });
        });

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

Is the format of this HTML tag correct?

I was provided with a code from our design department to add to a page, and since I am relatively new to the design aspect of things, I'm seeking clarification. Is this a valid tag? Also, what does <--if subcontent add rel="test1"--> mean? The c ...

Adjusting hyperlinks placement based on window size changes using jQuery

On resizing the screen, I am moving the sub-nav links to the '#MoreList' It works well initially, but when the window is expanded again, the links remain in the #MoreList instead of going back to their original positions if there is enough space ...

Slideshow feature stops working after one cycle

Hey there! I'm currently working on a function that allows for sliding through a series of images contained within a div. The goal is to cycle back to the beginning when reaching the end, and vice versa when going in the opposite direction. While my c ...

Fixing errors when utilizing multiple Axios requests for GET and POST requests

import React, { useState, useEffect } from "react"; import Axios from "axios"; import { Navigate, Link } from "react-router-dom"; import gravatarUrl from "gravatar-url"; import "../assets/css/profile.css"; ...

`A dynamically captivating banner featuring animated visuals created with JQuery`

I am currently in the process of designing a banner for the top of my webpage, but I have yet to come across any code that meets all my requirements. To provide clarification, I have attached an illustration showcasing what I am aiming to achieve. 1) The ...

How can I prevent a child div from activating the hover effect on its parent div?

I am currently exploring how to create a child element with position: absolute that is placed outside of its parent element without triggering the parent's :hover effect. Despite the parent having a hover effect, the child elements will still activat ...

Manipulating Strings in JavaScript

Hi there, I'm a beginner in JavaScript and I could really use some help with the following question. So, let's say I have this string: "AB_CD.1.23.3-609.7.8.EF_HI.XBXB" The numbers 1.23.3 and 609.7.8 are completely random with two dots separat ...

generate a new entry at the end of the list

I have a list and I am attempting to generate an element when the last row is clicked. It's a bit hard to explain, so here is the link to the jsfiddle: http://jsfiddle.net/ckgL3zxd/4/ When you click on the last row, you will notice that the element w ...

When an image in AngularJS is clicked, it should display a corresponding list

I'm brand new to Angular development. This is my very first solo project. My goal is to design a page where clicking on an image will display a list of items below it. For example, check out this link for reference: I've searched online for so ...

SweetAlert html is not recognizing ng-app, but it functions correctly within the html body

When inserting a bootstrap table inside a SweetAlert, I encountered an issue where using ng-app or ng-repeat to populate data inside the table's rows did not call ng-app. However, when populating the table outside of the SweetAlert in the body, ng-app ...

How to store lengthy JSON strings in SAP ABAP as variables or literals without extensive formatting restrictions

Is there a way to input lengthy JSON data into ABAP as a string literal without the need for excessive line breaks or formatting? Perhaps enclosing the string in a specific template, or utilizing a method similar to JSON.stringify(..) found in other langua ...

What adjustments need to be made on either the client-side or server-side in order to enable the functionality of getJSON()?

I recently encountered a challenge while working with web services that are hosted on a different domain from the site I am developing. This led me to explore calling these services using ajax, which introduced me to the complexities of the same-origin pol ...

Creating individual product pages from an array of objects: A step-by-step guide

Is there a way in Next.js to create individual pages for each object in an array with unique URLs? Here is the input array: Input Array const products = [ { url: "item-1", id: 1, name: "Item 1", description: "lor ...

Ways to place a background image without using the background-position attribute

On the menu of this page (blog.prco.com), I have added a background image for the hover effect on the elements. However, when hovering, the dot seems to move towards the final position from its origin point. My question is, how can I center the image belo ...

Start the BrightCove video by clicking on the link

I successfully integrated a Brightcove video into my mobile site and now I want to trigger it to play when the user clicks a link. Is there a way to access the video and start playing it using JQuery? <div id="video_player"><!-- Brightcove playe ...

Render data from a RESTful Express API using AJAX and Node.js to display on a webpage

New to node.js development and facing a specific issue. My goal is to build a single-page web app using node.js where users can submit request data, retrieve information from the IMDb API, and display it on the same page. Here's my code: server.js # ...

Why is it that injecting javascript within innerHTML seems to work in this case?

According to the discussion on this thread, it is generally believed that injecting javascript in innerHTML is not supposed to function as expected. However, there are instances where this unconventional method seems to work: <BR> Below is an examp ...

Footer div is being covered by the page

I am currently working on a website built with "WordPress", and I have implemented a mobile footer plugin that is designed to only appear on mobile devices. However, I am encountering an issue where the page content overlaps the footer on phones. I attemp ...

Using MithrilJS to dynamically pass variables to a configuration object when invoking the m() function

I am currently facing an issue while trying to implement the jQuery FooTable plugin in my mithril app. In my component, I have a config call that looks like this: view: function(ctrl, args) { return m("table#globalConfigTable", {config: executeFooTable} ...

Cannot get the before-leave transition JavaScript hook to function properly in Vue.js

I am facing an issue with my variable, transitionName, in the beforeLeaveHook function. Despite attempting to change it to 'left', the value remains stuck at 'right'. Any assistance on resolving this matter would be greatly appreciated. ...