Cookie handling functions


/ Published in: JavaScript
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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. }

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.