javascript - Using cookies to retain stylesheet preference across website -


i've got simple javascript function allows me swap between different stylesheets in each page of website. @ moment don't have cookies being implemented on site whenever go new page default stylesheet loaded , if user wanted use alternate stylesheet forced swap again. want make using cookies, whatever stylesheet user chooses remain when going different page.

below i've got following code 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 haven't been able webpage remember user chose stylesheet theme , when reloading page keep same stylesheet. first time working cookies , i'm looking way implement original javascript.

edit: heads up, know front end web programming @ point. based on dave a's answer, adapt current stylesheet() function follows or not necessary anymore? 1 thing i've had bit of hard time understanding how 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 use html 5 local storage store css filename:

store user's selection function like:

    function storestylesheet(stylesheetkey, stylesheetname){        localstorage.setitem(stylesheetkey, stylesheetname);     } 

and pull , use stored css, if there 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 easier use cookies. have not had problems using localstorage on browser. , interface intuitive; aware if file/keyname never stored before, return 'undefined' or undefined. there no automatic timeout localstorage.


Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -