How to Set & Read Javascript Cookies

A tutorial on how to set and read javascript cookies

By Rob Johnson

Sat Sep 05 2015

# tutorial # 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 # tutorial 14 # sql 3 # javascript 7 # projects 4 # git 2 # php 3 # analytics 3 # ux 1 # python 2 # aws 2 # mobile 1