Posted By

touffies on 11/12/10


Tagged

jquery cookies


Versions (?)

Plugin Cookies


 / Published in: jQuery
 

  1. /* ------------------------------------------------------------------
  2.   Plugin/Cookie ---------------------------------------------------- */
  3. $.cookie = function(name, value, options) {
  4. if (typeof value != 'undefined') { // name and value given, set cookie
  5. options = options || {};
  6. if (value === null) {
  7. value = '';
  8. options.expires = -1;
  9. }
  10. var expires = '';
  11. if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
  12. var date;
  13. if (typeof options.expires == 'number') {
  14. date = new Date();
  15. date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
  16. } else {
  17. date = options.expires;
  18. }
  19. expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
  20. }
  21. // CAUTION: Needed to parenthesize options.path and options.domain
  22. // in the following expressions, otherwise they evaluate to undefined
  23. // in the packed version for some reason...
  24. var path = options.path ? '; path=' + (options.path) : '';
  25. var domain = options.domain ? '; domain=' + (options.domain) : '';
  26.  
  27. var secure = options.secure ? '; secure' : '';
  28. document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
  29. } else { // only name given, get cookie
  30. var cookieValue = null;
  31. if (document.cookie && document.cookie !== '') {
  32. var cookies = document.cookie.split(';');
  33. for (var i = 0; i < cookies.length; i++) {
  34. var cookie = jQuery.trim(cookies[i]);
  35. // Does this cookie string begin with the name we want?
  36. if (cookie.substring(0, name.length + 1) == (name + '=')) {
  37. cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
  38. break;
  39. }
  40. }
  41. }
  42. return cookieValue;
  43. }
  44. };

Report this snippet  

You need to login to post a comment.