How do I set/unset a cookie with JavaScript


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

There is no need to use jQuery particularly to manipulate cookies.


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

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.