2

Probably has been already asked before but I still haven't found any useful or complete answer yet.How can we switch stylesheets and save the one that has been selected using jQuery cookie ? So I'm having like 5 stylesheets located in the same folder and the jQuery code below is automatically creating a select element.I can switch between the stylesheets but I don't know how to save the one that has been selected.Thank you.

<link href="styles/black.css" rel="stylesheet" type="text/css" title="black">
<link href="styles/blue.css" rel="stylesheet" type="text/css" title="blue">
<link href="styles/green.css" rel="stylesheet" type="text/css" title="green">
<link href="styles/red.css" rel="stylesheet" type="text/css" title="red">
<link href="styles/yellow.css" rel="stylesheet" type="text/css" title="yellow">

jQuery code:

<script type="text/javascript">
    (function($)
    {
        var $links = $('link[rel*=alternate][title]');
        $('#sw').prepend('<div id="toolbar"><select id="css-selector"></select></div>');
        var options= '<option value="">Select color:</option>';
        $links.each(function(index,value){
        options +='<option value="'+$(this).attr('href')+'">'+$(this).attr('title')+'</option>';
        });
    $links.remove();
    $('#css-selector').append(options)
    .bind('change',function(){
        $('link[rel*=jquery]').remove();
        $('head').append('<link rel="stylesheet jquery" href="'+$(this).val()+'" type="text/css" />');
    });
    }
    )(jQuery); 
    </script>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Eddi
  • 85
  • 1
  • 14

1 Answers1

3

Follow these step to create custom layout according to user cookie:-

  1. Create a function which read the cookie and change the default.css

    function readCookieCSS(){
        if($.cookie('styleSheet') === null || $.cookie('styleSheet')==undefined) {
            /*Do nothing*/
        }
        else{
            $('link[href="default.css"]').attr('href',$.cookie('styleSheet'));
        }
    }
    
  2. Changing the stylesheet and saving the css file name in cookie.

    function saveCSSinCookie(CSS_FILE_NAME){
        if($.cookie('styleSheet') === null || $.cookie('styleSheet')==undefined) {
            $.cookie("styleSheet", CSS_FILE_NAME, { expires : 365 });//expires after 1 year
            $('link[href="default.css"]').attr('href',$.cookie('styleSheet'));
        }
        else{
            $('link[href="'+$.cookie("styleSheet")+'"]').attr('href', CSS_FILE_NAME);
            $.cookie('styleSheet',CSS_FILE_NAME);
        }
    }
    

The basic idea behind these functions is if your cookie exist then stylesheet is saved by the user else the stylesheet is default.css (which in your case can be any one of the above styleSheet).

So, You have to call the readCookieCSS() on page load itself and the second function whenever you need to change the style.

Look into these answer if you want to learn more about stylesheet change and Jquery Cookie:-

  1. StyleSheet Change

  2. JQuery Cookie

Calling function in your code:-

  1. Add the readCookieCSS() when the page is load:-

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

  2. Add the saveCSSinCookie(CSS_FILE_NAME) is called when you change the stylesheet by updating your current bind function like this:-

    .bind('change',function(){ saveCSSinCookie($(this).val()); });

Updated Javascript as I am storing the different css value and title in javascript array $links Code:-

function readCookieCSS() {
    if ($.cookie('styleSheet') === null || $.cookie('styleSheet') == undefined) { /*Do nothing*/
    } else {
        $('link[href="default.css"]').attr('href', $.cookie('styleSheet'));
    }
}
function saveCSSinCookie(CSS_FILE_NAME) {
    if ($.cookie('styleSheet') === null || $.cookie('styleSheet') == undefined) {
        $.cookie("styleSheet", CSS_FILE_NAME, { expires : 365 });//expires after 1 year
        $('link[href="default.css"]').attr('href', $.cookie('styleSheet'));
    } else {
        $('link[href="' + $.cookie("styleSheet") + '"]').attr('href', CSS_FILE_NAME);
        $.cookie('styleSheet', CSS_FILE_NAME);
    }
}
$(document).ready(function()
{
    readCookieCSS();/*reading cookie on page load*/
    var $links = [{'style':'style/black.css','title':'black'}, {'style':'style/blue.css','title':'blue'}, {'style':'style/green.css','title':'green'}, {'style':'style/red.css','title':'red'},{'style':'style/yellow.css','title':'yellow'}];
    $('#sw').append('<div id="toolbar"><select id="css-selector"></select></div>');
    var options= '<option value="style/default.css">Select color:</option>';
    $links.map(function(value,index){
    options +='<option value="'+value.style+'">'+value.title+'</option>';
    });
    $('#css-selector').append(options)
    .bind('change',function(){
     saveCSSinCookie($(this).val());
});
}
); 

Using a default style sheet for the user for first time than changing stylesheet accordingly Updated CSS:

<link href="default.css" rel="stylesheet" type="text/css" title="black">

Working Example

Felk
  • 7,720
  • 2
  • 35
  • 65
Gaurav Kalyan
  • 1,897
  • 2
  • 14
  • 21
  • Thanks for your help but i can't manage to make it work..since the jquery cookie plugin is already included in my file ,i have added your two pieces of code after my jquery example and edited the default.css name from your example, but no results. What am i doing wrong? Thank you. – Eddi Dec 16 '14 at 15:50
  • You have defined the functions properly but you are not calling these functions. The first function `readCookieCSS()` will be called upon `$(document).ready(function({...});`. The second function `saveCSSinCookie(CSS_FILE_NAME)` will be called whenever you are changing the stylesheet. Please, suggest how are you changing the stylesheet so that second function can be added to it. – Gaurav Kalyan Dec 16 '14 at 15:56
  • Sorry but i don't understand what do you mean by "suggest how are you changing the stylesheet" ..My stylesheets are changing via my jquery code ( the select box is generated via that code ) . – Eddi Dec 16 '14 at 16:09
  • I got it, your are using change event in the "#css-selector" to update/ change the stylesheet. I have updated my code and declared where you have to call the functions, give them a try. :) – Gaurav Kalyan Dec 16 '14 at 16:15
  • I'm lost :) .Please put all your code (if i don't ask too much ),including mine all together on jsfiddle.I'm a newbie on jquery i must say. Billion thanks again. – Eddi Dec 16 '14 at 16:31
  • Creating a fiddle is bit tough if we are dealing with cookies and changing stylesheet as it is not supported by jsfiddle. Please try to find the errors you getting and share it here. So a solution can be found out. – Gaurav Kalyan Dec 16 '14 at 16:54
  • I didn't expected to have it working already, i just wanted to see the full code how it looks like,cause i don't know were to insert your edits.. – Eddi Dec 16 '14 at 16:59
  • I have updated code added the fiddle link in the code. Please see it and try it. – Gaurav Kalyan Dec 16 '14 at 17:53
  • Almost done.Thank you very much sir. I can see the cookie saved but it doesn't activate the selected stylesheet anymore ( it doesn't change the colors anymore ) and when i refresh the page the "select color" text is visible again.Any ideea? – Eddi Dec 17 '14 at 18:39
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/67155/discussion-between-gaurav-kalyan-and-eddi). – Gaurav Kalyan Dec 17 '14 at 19:14
  • I am so sorry. There was a typo error in the saveCSSinCookie code. I have updated it. Please check again. – Gaurav Kalyan Dec 18 '14 at 09:18
  • I've just implemented a simple system for saving cookie on a twin themed webpage based on this answer. Perfect! Thanks. – James McCormac Nov 22 '16 at 23:59