clubmate.fi

A good[ish] website

Web development blog, loads of UI and JavaScript topics

Setting and reading cookies with JavaScript

Filed under: JavaScript— Tagged with: cookie, jquery

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

Pure JavaScript

Here’s a set of functions that create, read, and erase cookies:

function createCookie(name, value, days) {
  var expires

  if (days) {
    var date = new Date()
    date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000)
    expires = '; expires=' + date.toGMTString()
  } else {
    expires = ''
  }

  document.cookie = name + '=' + value + expires + '; path=/'
}

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
}

function eraseCookie(name) {
  createCookie(name, '', -1)
}

Source

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:

readCookie('cookie-name')
// 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:

$.cookie('cookie-name')

Read more about advanced usage of it.

Comments would go here, but the commenting system isn’t ready yet, sorry.

  • © 2022 Antti Hiljá
  • About
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!