JavaScript Cookies - Baking Has Never Been So Easy!


Typically when I'm working on a site everything has either a .php extension or is Apache rewrite_moded to a PHP file.

Though this is an obvious thing for me to do it isn't so obvious for some of the people I've worked with or some clients whom I've needed to make updates for. So when I suddenly needed to retrieve a query string and make it available site wide I had to go back to cookies with JavaScript.

First I searched the web for the best functions to set, get and delete my cookies. No one site seemed to get all of it right so I had to do a little leg work of my own.
It's been probably 3 years since I set a JavaScript cookie by hand. Back in my INT220 class at AI I believe (Hi Dale and thanks for all the smarts you done gave me!)

Before you can work with a JavaScript cookie, you have to set one, which is why part one of our lesson is:

Setting a Cookie with JavaScript

Broken down setting cookies with JavaScript is easy-peasy:

JavaScript

document.cookie = "CookieName=CookieValue; expires=Monday, 31-Dec-2010 23:59:59 GMT; path=/; domain=.example.com; secure";

That will set the cookie CookieName with the value CookieValue which will expire at the end of 2001 set to the root path and the domain example.org (including sub domains) and it's secure (https),

Now that's great but a function, that's even better. Especially since everything after the key=value pair (in this case CookieName=CookieValue) is optional.

I saw plenty of functions where if you passed expires as empty it would set the cookie to expire in a day or a couple hours but I want to be able to set that individually or have the cookie default to be a session cookie. So I found a function and modified it into this:

JavaScript

function setCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toUTCString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}

The name of the cookie and value is pretty self explanatory so we'll skip straight to the expire parameter.

Expire

As I said before if you pass nothing or an empty/null value as the expire parameter it will be a session cookie, one that expires when the browser is closed. To set the expiration time you need to pass a date which will be transformed into the appropriate format inside the function.

So if you want to set a cookie that will expire in 22 hours, try:

JavaScript

var expDate = new Date();
expDate.setHours( parseInt(expDate.getHours()) + 22 );
setCookie('CookieName', 'CookieValue', expDate) ;

Here's a quick synopsis of how to set other relative dates:

  • 45 seconds in the future
    expDate.setSeconds( parseInt(expDate.getSeconds()) + 45 );
  • 30 minutes in the future
    expDate.setMinutes( parseInt(expDate.getMinutes()) + 30 );
  • 5 hours in the future
    expDate.setHours( parseInt(expDate.getHours()) + 30 );
  • 7 days in the future
    expDate.setDate( parseInt(expDate.getDate()) + 7 );
  • 6 months in the future
    expDate.setMonth( parseInt(expDate.getMonth()) + 6 );
  • 1 year in the future
    expDate.setYear( parseInt(expDate.getYear()) + 1 );

Easy enough!

Path

By default a cookie with no value set for path will set the cookie relative to the path you are in. So if the cookie is set in the example.com/test/javascript/index.html page the cookie will be set with a path of /test/javascript/
I usually force my cookies with a path to the root / to ensure I don't have problems with the cookie anywhere on the site.

Domain

There's multiple ways to set this, though I stick with the default (which is whatever domain you are in when you set the cookie.)

  • example.com
  • .example.com - (includes all sub domains)
  • subdomain.example.com

If you need to access this cookie from sub domains you need to make sure that the . precedes the domain name. As a rule of thumb, omit the www.

Secure

I don't do a lot with SSL but if I needed to set a cookie in teh secure portion of https://example.com you would have to pass secure (as itself, there is no pairing here and it is not boolean) to ensure there are no problems.

Download

Download the complete JavaScript file functions.cookies.js

Continue on to page 2: deleting, updating and retrieving JavaScript cookies...

Information and Links

Join the fray by commenting, tracking what others have to say, or linking to it from your blog.


Similar Entries
Extending JavaScript to Trim
As of lately I have become, well, obsessed with the Prototype JavaScript library. There is, as there always is, heated discussions across the internet of the benefits/strengths/weaknesses of many readily-available JavaScript libraries. Such as: Prototype MooTools jQuery Mochikit Dojo Toolkit Yahoo! UI Libray Google Web Toolkit But for the time being, all those libraries are irrelevant. It's great how easy they are
MySQL Queries Made Easy With PHP Functions Library
Every web developer has a library of code that they reference frequently, if not constantly. I'm sharing with you one of my most useful snippets my MySQL helper class that helps me organize my queries and easily reference commonly used functions.
Relative Dates in WordPress Templates
One of my favorite trends online is using relative dates like '1 week ago' or '4 days ago' instead of the standard June 11, 2008. I find it helpful in really getting a feel for the freshness of an entry or comment and it's super easy to implement in WordPress.
From Query String to Cookie with JavaScript
Take a query string and save the values to a cookie using JavaScript. A perfect solution for tracking query string's values throughout a site that isn't using any server side scripting.
Zip Code, Phone Number and Replacing Empty Fields with Really Easy Validation
While using the Really Easy Validation JavaScript validation library I've accumulated a few custom validations that for US phone numbers, US zip codes, Canadian postal codes as well as replacing empty fields or fields that don't contain a numeric value. Good stuff!
Next Post
Chumby Control Panel Updates
Previous Post
Zip Code, Phone Number and Replacing Empty Fields with Really Easy Validation

Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Reader Comments

Be the first to leave a comment!