Posted By

pmw57 on 12/20/10


Tagged

javascript cookie cookies


Versions (?)

Cookie handling functions


 / Published in: JavaScript
 

URL: http://www.quirksmode.org/js/cookies.html

Cleaned up (with the help of jslint.com) versions of cookie handling functions

  1. function createCookie(name, value, days) {
  2. var expires = '',
  3. date = new Date();
  4. if (days) {
  5. date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
  6. expires = '; expires=' + date.toGMTString();
  7. }
  8. document.cookie = name + '=' + value + expires + '; path=/';
  9. }
  10.  
  11. function readCookie(name) {
  12. var nameEQ = name + '=',
  13. allCookies = document.cookie.split(';'),
  14. i,
  15. cookie;
  16. for (i = 0; i < allCookies.length; i += 1) {
  17. cookie = allCookies[i];
  18. while (cookie.charAt(0) === ' ') {
  19. cookie = cookie.substring(1, cookie.length);
  20. }
  21. if (cookie.indexOf(nameEQ) === 0) {
  22. return cookie.substring(nameEQ.length, cookie.length);
  23. }
  24. }
  25. return null;
  26. }
  27.  
  28. function eraseCookie(name) {
  29. createCookie(name, '', -1);
  30. }

Report this snippet  

You need to login to post a comment.