On this page I give three functions to save, read and erase cookies with JavaScript (No need jQuery). Using these functions you can manage cookies on your site.
The function is document.cookie and 3 functions is:
1. setCookie():
function setCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = '; expires="+date.toGMTString(); } else var expires = ''; document.cookie = name+ '=' + value + expires + '; path=/'; }
- name: the cookie name
- value: value of this cookie
- days: cookie expires
2. readCookie(name)
function readCookie(name) { var nameEQ = name + '='; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; }
- name: the cookie name
- this function return a string
3. deleteCookie():
function deleteCookie(name) { setCookie(name,'',-1); }