Posted By

noah on 05/02/07


Tagged

regex cookies persistent state ui ux preferences tracking


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

vali29


Save application state in a cookie


 / Published in: JavaScript
 

A variant of this code is in use on the My Organizer app at http://collegeboard.com/student/index.html?student

  1. function cookieTime(days){
  2. var now = new Date();
  3. var exp = new Date();
  4. var x = Date.parse(now) + days*24*60*60*1000;
  5. exp.setTime(x);
  6. str = exp.toUTCString();
  7. re = '/(\d\d)\s(\w\w\w)\s\d\d(\d\d))/';
  8. return str.replace(re,"$1-$2-$3");
  9. }
  10.  
  11. //set cookie:
  12. var cookieName; //should be set to something unique
  13. var stateAsString; //should be set to a string indicative of the state being saved
  14. document.cookie = someString+'='+stateAsString+';path=/;expires='+cookieTime(365);
  15.  
  16. //get cookie
  17. var re = new RegExp(cookieName+'=(.*)');
  18. var state = re.exec(document.cookie);
  19. var lastState = (state) ? state[1].split(';')[0] : 'default state';
  20.  
  21. /* or, more formally */
  22. var cookieJar: {
  23. setState: function ( id, value) {
  24. document.cookie = id+'='+value+';path=/;expires='+cookieTime(365);
  25. },
  26. getState: function( id, defaultState ) {
  27. var re = new RegExp(id+'=(.*)');
  28. var state = re.exec(document.cookie);
  29. return (state) ? state[1].split(';')[0] : defaultState;
  30. }
  31. }

Report this snippet  

You need to login to post a comment.