If we want to create, update (change) or remove cookies in JavaScript we must do a few very simple operations like I described below. This is quite common situation in everyday JavaScript development when we want to make some operations based on cookies. Cookies are used to store small pieces of textual information and has the expiry date. After that day cookie will be removed from the browsers memory. This is good to store in cookies, and use create, change, remove and delete operations, in e.g. forms, shopping carts etc.
Table of Contents
Step 1 – Prepare an expiration date for a cookie
I usually use below function to define the expiration date of the cookie. Function takes time in minutes as argument, adds it to current time, and returns expiration time and date (current time + minutes from argument):
function setTimeForCookies (minutes) { var now = new Date(); var time = now.getTime(); time += minutes * 60 * 1000; now.setTime(time); return now; }
Step 2 – Create a cookie
I create a cookie in very common way, like presented below. To set “expires” parameter I use above function:
document.cookie = "cookieName=This is a cookie value; expires=" + setTimeForCookies(60) + "; path=/";
Step 3 – Update cookie expiration date
As I mentioned on the beginning of the post, to update expiration date we must do the same things like in step 2, with new date. So, in general terms, it is not updating cookie but rewriting it. In the same way we can update/rewrite cookie value:
document.cookie = "cookieName=This is a NEW cookie value; expires=" + setTimeForCookies(120) + "; path=/";
Step 4 – remove cookie
To remove a cookie we must update its expiration date, but we must set date somewhere in the PAST! Then automatically, cookie become expired and will be deleted by a browser. The best way is to set the date: 1 January 1970 – of course in right format: “Thu, 01 Jan 1970 00:00:01 GMT” (unix time).
document.cookie = "cookieName=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/";
I use usually below function to remove many cookies:
function clearCookies (names) { var i = 0, namesLength = names.length; for (i; i < namesLength; i += 1) { document.cookie = names[i] + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/'; } } clearCookies(["cookieName1", "cookieName2"]);
Code in this post is very simple. I wanted just to show you basic operations on cookies.