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. var 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. function readCookie(name) {
  11. var nameEQ = name + "=";
  12. var allCookies = document.cookie.split(";");
  13. allCookies.forEach(function (cookie) {
  14. while (cookie.charAt(0) === " ") {
  15. cookie = cookie.substring(1, cookie.length);
  16. }
  17. if (cookie.indexOf(nameEQ) === 0) {
  18. return cookie.substring(nameEQ.length, cookie.length);
  19. }
  20. });
  21. }
  22. function eraseCookie(name) {
  23. createCookie(name, "", -1);
  24. }

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

Report this snippet


Comments


You need to login to view comments.