Setting and reading cookies with JavaScript

Here's two different methods to read and write cookies using JavaScript and/or jQuery.

Pure JavaScript

Here’s a set of functions:

// Create cookie
function createCookie(name, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        expires = "; expires="+date.toGMTString();
    else {
        expires = "";
    document.cookie = name+"="+value+expires+"; path=/";

// Read cookie
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;

// Erase cookie
function eraseCookie(name) {


It takes three parameters:

  • Cookie name
  • Cookie value
  • Cookie expire date (in days e.g. 7)

To set a cookie:

createCookie("cookie-name", "cookie-value", 30);

To read a cookie:

// Usually you set it as a variable and then use it somewhere
var colorTheme = readCookie("color-theme");
// Then do some conditional crap with it
if (colorTheme == "Blue") {
    // Add a class to the body or elswere
} else {
    // Add a different class maybe...

I’ve been using this and never had any problems with it. It’s really small and library independent!

If you’re using CodeKit, consider leveraging the Kit language, and include the functions to your main.js file:

//@codekit-prepend "_cookies-vanilla.js";

jQuery plugin

There’s also a jQuery Cookie plugin to make the task of setting cookies easier. Honestly, I prefer the vanilla JS method. The jQuery Cookies plugin is bigger and then you are limited to that library (witch really isn’t that big of a problem, usually people are really library loyal).

I’m a big fan of limiting http calls, so it’s recommended to include it in the beginning of your main JS file, same way as above:

//@codekit-prepend "_cookies-jquery-plugin.js";

Create a cookie:

$.cookie('cookie-name', 'cookie-value');

Read a cookie:


Read more about advanced usage of it.


Club-Mate, the beverage →