Javascript - Cookies


// JavaScript - Cookie

Cookies are the small text files stored in a computer and they are created when 
the user visits the websites to store information that they need. Example could 
be User Name details and shopping cart information from the previous visits.
The cookies are sent to the server on every subsequent requests.

// Read all the cookies:

// You will see is a long string of semi-colon delineated key/value pairs:

// You can manually set a cookie by setting document.cookie equal to the 
// desired cookie using this format:
document.cookie = "name=tyler;expires=Thu, 03 Sep 2015 05:33:44 GMT";

function setCookie(name, value, exdays) {
    var d, expires;
    exdays = exdays || 1;
    d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    expires = "expires=" + d.toUTCString();
    document.cookie = name + "=" + value + "; " + expires;

To read a cookie you can simply access document.cookie.

If you're searching for a specific value you can use the following function:
function getCookie(name) {
    var cookie, c;
    cookies = document.cookie.split(';');
    for (var i=0; i < cookies.length; i++) {
        c = cookies[i].split('=');
        if (c[0] == name) {
            return c[1];
    return "";

To delete a cookie, you simply need to expire it. So deleting a cookie is 
basically setting the cookie with an expiration in the past. 
Using our setCookie function:
setCookie('name', '', -1);

If you're using jQuery, you might as well use this cookie plugin. It allows 
easy management of cookies:

// read
$.cookie('name'); // => "Batman"
// set
$.cookie('name', 'Iron Man');
// delete

Set-Cookie: NAME=VALUE [;expires=DATE][;path=PATH][;domain=DOMAIN][;secure]

// The date is specified in the format: Weekday, DD-Mon-YY HH:MM:SS GMT

Cookie: NAME1=VALUE1;NAME2=VALUE2; // Browser sending matching cookies to server

document.cookie="..."; // Using JavaScript to manipulate cookies on the client side
var cookieString = document.cookie;
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License