Using jQuery cookies to create a CSS style switcher

I've been experimenting with creating a jQuery stylesheet switcher and have had some success. However, I'm running into an issue when trying to save the changes in a cookie using the jquery.cookie plugin.

Here's the snippet of jQuery code that I'm working with:

$("#theme-cp ul li").click(function () {
    var $pattern = $(this).css("background-image");
    $("body").css("background-image",$pattern);
    $("#main-wrapper").css("background-image",$pattern);
    $.cookie('background',$pattern);
    alert($.cookie('background'));
});

I added the alert for troubleshooting purposes, but it seems like it's not functioning as expected...

Answer №1

I recently accomplished the same task and managed to make it work. Here is the code I used:

jsFiddle

jQuery

//Checking if there is a cookie set
if($.cookie('colour')!='')
{
    $('body').addClass($.cookie('colour'));
}

$('#accessibility-colours a').each(function(index)
{
    $(this).click(function(e)
    {
        e.preventDefault();

        switch(index)
        {
            case 0:
                $('body').removeClass($.cookie('colour'));
                $('body').addClass('blackText-whiteBackground');
                $.cookie('colour', null);
                $.cookie('colour', 'blackText-whiteBackground',{ expires: 7, path: '/' });
            break;

            case 1:
                $('body').removeClass($.cookie('colour'));
                $('body').addClass('blackText-yellowBackground');
                $.cookie('colour', null);
                $.cookie('colour', 'blackText-yellowBackground',{ expires: 7, path: '/' });
            break;

            case 2:
                $('body').removeClass($.cookie('colour'));
                $('body').addClass('blackText-pinkBackground');
                $.cookie('colour', null);
                $.cookie('colour', 'blackText-pinkBackground',{ expires: 7, path: '/' });
            break;

            case 3:
                $('body').removeClass($.cookie('colour'));
                $('body').addClass('blueText-whiteBackground');
                $.cookie('colour', null);
                $.cookie('colour', 'blueText-whiteBackground',{ expires: 7, path: '/' });
            break;

        }
    });

CSS

html, body                              {font:0.9em/1.1em "Arial", sans-serif}

/* Accesibility Icons */
#accessibility-colours                  {margin:0px; overflow:hidden;}
#accessibility-blackWhite               {background:url(../images/design/icon-accessibility-blackWhite.gif) 0 0 no-repeat}
#accessibility-blackYellow              {background:url(../images/design/icon-accessibility-blackYellow.gif) 0 0 no-repeat}
#accessibility-blackPink                {background:url(../images/design/icon-accessibility-blackPink.gif) 0 0 no-repeat}
#accessibility-blueWhite                {background:url(../images/design/icon-accessibility-blueWhite.gif) 0 0 no-repeat}

    #accessibility-colours a            {float:left; display:block; margin:6px 0 0; padding:4px; border:0; width:16px; height:16px;}
    #accessibility-colours a span       {margin:0; padding:0; position:absolute; top:-9999px; left:-9999px;}


.blackText-whiteBackground              {background:white; color:black}
.blackText-yellowBackground             {background:yellow; color:black}
.blackText-pinkBackground               {background:pink; color:black}
.blueText-whiteBackground               {background:white; color:blue}

HTML

<div id="accessibility-colours">
        <a id="accessibility-blackWhite" href="#" title="Black text / White background"><span>Black text / White background</span></a>
        <a id="accessibility-blackYellow" href="#" title="Black text / Yellow background"><span>Black text / Yellow background</span></a>
        <a id="accessibility-blackPink" href="#" title="Black text / Pink background"><span>Black text / Pink background</span></a>
        <a id="accessibility-blueWhite" href="#" title="Blue text / White background"><span>Blue text / White background</span></a>
    </div>

    <h1>This is the H1 tag</h1>

    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam facilisis nibh sed tortor blandit interdum semper leo ullamcorper. 
    Pellentesque gravida hendrerit accumsan. Mauris pretium blandit augue, suscipit ultricies libero aliquam sit amet. Aliquam egestas eleifend augue, 
    et hendrerit dolor dictum facilisis. Nulla facilisi. Integer auctor elementum purus id lobortis. Aliquam sit amet sem erat. Integer nec orci risus. 
    Quisque eu purus augue. Sed vehicula venenatis metus eget molestie. Proin vel ultrices augue. Duis in laoreet tellus. Proin eget gravida purus. 
    Donec ut placerat velit. Etiam ultrices, nibh nec ultricies iaculis, odio orci porta dui, quis semper nunc ante interdum augue. 
    Curabitur elementum orci interdum nibh adipiscing blandit. Curabitur diam arcu, semper id facilisis id, tempor et nisi. 
    Vestibulum nisl dolor, aliquam et posuere ut, tincidunt sed mi.</p>

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

Error when spaces are present in the formatted JSON result within the link parameter of the 'load' function in JQuery

I am facing an issue with JSON and jQuery. My goal is to send a formatted JSON result within the link using the .load() function. <?php $array = array( "test1" => "Some_text_without_space", "test2" => "Some text with space" ); $json = jso ...

Odd floating and positioning behavior observed in IE7

Looking for help with this code: <div class="container"> <input type="submit" name="submit" class="submit" value="Sign Up"> </div> Check out the CSS styling: input.submit{ padding-left: 40px; padding-right: 40px; float: ...

jQuery unable to find designated elements in uploaded templates

I have a specific route linked to a specific controller and view: app.config(['$routeProvider', function ($routeProvider) { $routeProvider .when('/create', { templateUrl: 'partials/form/form.html', controlle ...

Retrieving solely the JSON data output from an AJAX request

I'm working with the following script: var test = $.ajax({ url : ("/areas/list"), type : 'GET', dataType : 'json', success : function(e) { // code here } }); The result stored in var text looks li ...

What is the best way to remove the background transparency of an image?

Images are being shown inside an HTML table using PHP code : This is the code for the table : for ($i = 0; $i < $data['list']['cnt']; $i++) { $tabRows[$i][1]['width'] = "45%"; $tabRows[$i][1][&apos ...

Switch Picture on Active List Item

I've implemented a two-tab content slider specifically for the mobile section of my website. Users can click on the linked image within the <li> element to load the corresponding content. My goal is to have the image change color when in an "act ...

The Bootstrap tab feature is malfunctioning when a tab is using data-target instead of href

While developing bootstrap tabs for an Angular app, I decided to use the data-target attribute instead of the href attribute to avoid any interference with routes. Here's a snippet of how I structured the tabs: <ul class="nav nav-tabs" id="myTab"& ...

A div with an absolute position containing a header, content, and footer

How can I place a header, content, and footer inside a div element with absolute positioning, where the position value cannot be changed? The header and footer have fixed heights, and the content should occupy the remaining space. The header should always ...

Triggering an Ajax call for form validation only occurs when the form is not validated

I am struggling with a simple form that has an Ajax call, but the ajax call gets executed even if the form is not validated. In the code snippet below, the line console.log("This line should execute only if Form is validated"); gets executed when the form ...

How to vertically center a form element in Bootstrap 4

As a newbie to using bootstrap 4 for the first time, I expected vertical alignment of elements to be easy, especially with flex being touted as the simplest way to achieve this. The issue: Struggling to vertically align my form element within my navigatio ...

Meteor Js Boostrap Menu Formatting Challenges

Greetings and good afternoon. I am currently working on developing a social networking application using the Meteor Js Stack, but I am encountering some issues with my navigation bar wrapping on mobile devices. Despite setting my dropdown to pull-right, it ...

Combining HTML, CSS, and Javascript to create a single JS file

I am designing a form component from scratch, free of any frameworks. My aim is to provide clients with a simple solution by delivering the component through a single JavaScript file. All they will need to do is create a div element with a specific id, and ...

Hover functionality for picture

Is there a way to create a voting system that appears on an image when hovered over with the mouse? For instance, take a look at the images in this widget: http://jsfiddle.net/4B2Bc/. I'm interested in having a thumbs up or thumbs down icon display w ...

Motion, animated image while the script is being executed

I've developed a script named notify_me.php which I execute in the following manner: script type="text/javascript"> //Running notify_me.php script $(document).ready(function(){ $("#submit").click(function(){ var d = $(&ap ...

The method 'addMethod' cannot be executed as it is referencing an undefined object

Encountering an error message "cannot call method 'addMethod' of undefined" while the browser is running the following code snippet. $.validator.addMethod("regex", function (value, element, param){ return this.optional(element) || param.test ...

Why ASP .NET MVC's AJAX BeginForm InsertionMode.Replace feature is causing issues

When I input anything into the text field, I can see the result displayed in the desired DIV. However, upon inspecting the page's source code, I cannot locate the replacement element. For instance, if I input 'aaaaaaaaaaaaaaaa', then click ...

Using jQuery to dynamically format a date with variables

Looking to properly format a date for use in a compare function to sort data $(xml).find("item").each(function () { var dateText = $(this).find("Date").text(); var year = dateText.substr(0,4); var month = dateText.subst ...

Breaking columns in Firefox using CSS

I am currently exploring a cross-browser approach to create a columned layout for an unordered list. The content is generated by a CMS, so my options are limited to adding classes only. While I have been successful in creating columns, I also need to contr ...

The text of a list item wraps underneath the marker before filling the rest of the available space

I'm facing an issue where text in a list item is being pushed to the line below the bullet point. I want the text to fill the first line with the bullet before wrapping to the next line without using list-style-position: outside. Here is my CSS: .list ...

Positioning a Safari browser relative to a flex container

Seeking assistance with positioning elements in Safari 602.1 on iOS 10 using Bootstrap 4.1. The text isn't positioned correctly, even after auto-prefixing Bootstrap. The issue only occurs in Safari; everywhere else, it works fine and I'm at a lo ...