How to Set & Read Javascript Cookies

A few pointers on how to set and read javascript cookies

By Rob Johnson

Sat Sep 05 2015

dev javascript

Here are a few tricks with javascript that can be adapted for many uses. That said, the users browser will need to have javascript enabled. The following code doesn't require jQuery.

Step 1: Create a cookie

document.cookie="cookiename=cookievalue";

Step 2: Initial script to allow you to read cookies

var cookies;

function readCookie(name,c,C,i){
if(cookies){ return cookies[name]; }

c = document.cookie.split('; ');
cookies = {};

for(i=c.length-1; i>=0; i--){
C = c[i].split('=');
cookies[C[0]] = C[1];
}

return cookies[name];
}

window.readCookie = readCookie; // or expose it however you want

Step 3: Request the value of a specific cookie

readCookie("cookiename");

commerce 4 seo 3 productivity 1 dev 15 sql 1 tutorial 2 javascript 7 git 2 php 3 analytics 3 projects 3 ux 1 teams 1 mobile 1