简体   繁体   中英

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>

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 .

It would probably be easiest to pull in all the CSS (unless it's massive) and then apply a theme class to body/wherever you need it. And your CSS would look like

// common and default definitions

body.some-theme{
  // theme overrides of default go here
}

body.some-other-theme{
  // another theme
}

If you want a solution that remembers the user rather than the browser/ip address (remembering each browser has its own cookie jar) you'd probably best write this in a server side language with user preferences and only output the relevant CSS file using some server side processing.

However that's a much bigger question, to quickly solve the issue at hand consider the following.

Start by loading all CSS files, assuming they're not huge it probably won't make much difference speed wise, and it would mean the user could switch without the overhead of downloading extra data.

I agree with Dave A that the localStorage method is probably the best way to go about storing this info (without a server storing user preferences). So I suggest you write something similar to the following, I hacked this together rather quickly as I'm sure is rather apparent.

<!DOCTYPE html>
<html>
  <head>
    <style>
      .default {
        background-color: blue;
      }

      .alternative {
        background-color: red;
      }
    </style>
    <script type='text/javascript'>
      function init() {
        if (localStorage.getItem('cssName') !== "default") {
          var i = 0;
          var elems = [];
          var elements = document.getElementsByClassName('default');

          // Put the elements into an easy to interate array instead of HTML Collection.
          for (i = 0; i < elements.length; i++) {
            elems.push(elements[i]);
          }

          // Iterate over the new nice array.
          elems.forEach(function(element, index, array) {
            element.setAttribute('class', 'alternative');    
          });
        }
      }
    </script>
  </head>

  <body onload='init();'>
    <div class='default'>hbdfisubfiuodfhriubsrfiub</div>
    <div>iboufruewhiobieiohhbefpijbepojb</div>
    <div class='default'>hbdfisubfiuodfhriubsrfiub</div>
    <div>iboufruewhiobieiohhbefpijbepojb</div>
    <div class='default'>hbdfisubfiuodfhriubsrfiub</div>
    <div>iboufruewhiobieiohhbefpijbepojb</div>
    <div class='default'>hbdfisubfiuodfhriubsrfiub</div>
    <div>iboufruewhiobieiohhbefpijbepojb</div>
  </body>
</html>

I forgot to mention this if you wish to go down the local storage route: http://mozilla.github.io/localForage/?javascript#localforage

Might be worth reading about.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM