LearnFast.Ninja

JavaScript cookie example code

In this tutorial will show you how to use the document cookie in JavaScript. You will see how to set cookie, how to get cookie and also how to delete the cookie. There are few way of cookie expiration you will see them.

Step 1: First you must need to have these set of functions to set, get and delete cookie.

//-- Cookies - START ------------------------------

function setCookie(name, value, days) {

    var expires = "";

    if (days) {

        var date = new Date();

        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));

        expires = "; expires=" + date.toGMTString();

        document.cookie = name + "=" + value + expires + "; path=/";

    }

    else {

        document.cookie = name + "=" + value + expires + "; path=/";

    }

}

 

function getCookie(name) {

    var nameWithEqual = name + "=";

    var cookieSplit = document.cookie.split(';');

    for (var i = 0; i < cookieSplit.length; i++) {

        var c = cookieSplit[i];

        while (c.charAt(0) == ' ') {

         c = c.substring(1, c.length);

        }

        if (c.indexOf(nameWithEqual) == 0) return c.substring(nameWithEqual.length, c.length);

    }

    return null;

}

 

function deleteCookie(name) {

    setCookie(name, "", -1);

}

//-- Cookies - END --------------------------------


Step 2: This is how you use the cookies. Check if it is not null then you know the cookie is exist else you need to set it.

if (null != getCookie('cart')) {

    getCookie('cart')

}

else {

    setCookie('cart''camera');

}


Result:



Cookie expiration:

// Example for 1 day:  

setCookie('myCookie''myValue', 1);

 

// Example for ~1 hour: 

setCookie('Hover_Search''Close', 0.016);

 

// Example for session end:  

setCookie('myCookie''myValue');


Tags

javascript

document.cookie cookies cookie cookie-expiration