Valrok Valrok - 5 months ago 12
jQuery Question

Using cookies to retain stylesheet preference across website

I've got a simple javascript function which allows me to swap between different stylesheets in each page of my website. At the moment I don't have any cookies being implemented on the site so whenever I go to a new page the default stylesheet is loaded and if a user wanted to use the alternate stylesheet they would be forced to swap again. I want to make it to where by using cookies, whatever stylesheet the user chooses will remain when going to a different page.

Below I've got the following code which is my method of swapping stylesheets.

<script type="text/javascript">
var i=1;
function styleSheet(){
if(i%2==0){
swapper('css/main.css');
}
else{
swapper('css/stylesheetalternate.css');
}
i++;
}
</script>
<script>
function swapper(select_sheet){
document.getElementById('swapper').setAttribute('href', select_sheet);
}
</script>


So far I haven't been able to get it to where the webpage would remember what the user chose as their stylesheet theme and when reloading the page keep the same stylesheet. This is my first time working with cookies and I'm mostly just looking for a way to implement this with my original javascript.

EDIT: Also just as a heads up, I only know front end web programming at this point. Based on Dave A's answer, would I adapt my current styleSheet() function as follows or is this not even necessary anymore? One thing I've had a bit of a hard time understanding is how the key works.

<script type="text/javascript">
var i=1;
function styleSheet(){
if(i%2==0){
storeStyleSheet(sheet1, main.css);
}
else{
storeStyleSheet(sheet2, alternate.css);
}
i++;
}
</script>
<button onclick()="setStoredStyleSheet (styleSheetKey)">click here</button>

Answer

I would use HTML 5 local storage to store the CSS filename:

Store the user's selection with a function like:

    function storeStyleSheet(styleSheetKey, StyleSheetName){
       localStorage.setItem(styleSheetKey, StyleSheetName);
    }

And pull and use the stored CSS, if there is one:

    function setStoredStyleSheet(styleSheetKey){
    var styleSheet = localStorage.getItem(styleSheetKey);
        if(!(styleSheet=='undefined' || styleSheet==undefined) ){
            swapper(styleSheet);            
        }
        else{
            swapper('css/stylesheetalternate.css');             
        }
    }

I have found HTML 5 local storage to be easier to use than cookies. I have not had any problems using localStorage on any browser. And the interface is intuitive; just be aware that if the file/keyname was never stored before, it will return 'undefined' or undefined. There is also no automatic timeout with localStorage.