1297

How do I set and unset a cookie using jQuery, for example create a cookie named test and set the value to 1?

Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
omg
  • 123,990
  • 135
  • 275
  • 341

15 Answers15

1819

Update April 2019

jQuery isn't needed for cookie reading/manipulation, so don't use the original answer below.

Go to https://github.com/js-cookie/js-cookie instead, and use the library there that doesn't depend on jQuery.

Basic examples:

// Set a cookie
Cookies.set('name', 'value');

// Read the cookie
Cookies.get('name') => // => 'value'

See the docs on github for details.


Before April 2019 (old)

See the plugin:

https://github.com/carhartl/jquery-cookie

You can then do:

$.cookie("test", 1);

To delete:

$.removeCookie("test");

Additionally, to set a timeout of a certain number of days (10 here) on the cookie:

$.cookie("test", 1, { expires : 10 });

If the expires option is omitted, then the cookie becomes a session cookie and is deleted when the browser exits.

To cover all the options:

$.cookie("test", 1, {
   expires : 10,           // Expires in 10 days

   path    : '/',          // The value of the path attribute of the cookie
                           // (Default: path of page that created the cookie).

   domain  : 'jquery.com', // The value of the domain attribute of the cookie
                           // (Default: domain of page that created the cookie).

   secure  : true          // If set to true the secure attribute of the cookie
                           // will be set and the cookie transmission will
                           // require a secure protocol (defaults to false).
});

To read back the value of the cookie:

var cookieValue = $.cookie("test");

You may wish to specify the path parameter if the cookie was created on a different path to the current one:

var cookieValue = $.cookie("test", { path: '/foo' });

UPDATE (April 2015):

As stated in the comments below, the team that worked on the original plugin has removed the jQuery dependency in a new project (https://github.com/js-cookie/js-cookie) which has the same functionality and general syntax as the jQuery version. Apparently the original plugin isn't going anywhere though.

PJunior
  • 2,267
  • 28
  • 28
Alistair Evans
  • 33,072
  • 6
  • 32
  • 48
  • 1
    from the changelog: "$.removeCookie('foo') for deleting a cookie, using $.cookie('foo', null) is now deprecated" – bogdan Jan 07 '13 at 03:57
  • Plugin works great, expect its only storing a session cookie on the latest version of Opera as of 5-31-13 (v12.15). Persistent cookies works in IE, Chrome, FF, and Safari, but just not Opera. – johntrepreneur Jun 01 '13 at 01:45
  • To test if a cookie is set: `var mytest = $.cookie('nameofcookie');`
    `if (typeof mytest === "undefined") { alert("cookie mytest not set") }`
    – cssyphus Jun 14 '13 at 20:21
  • @AndreiCristianProdan - Doesn't it? Why not? I can't imagine the behaviour would be any different. – Alistair Evans Jul 02 '13 at 08:26
  • 73
    @Kazar I spent 6 hours, no breaks. I finally realized the problem this morning. I'm using this with phonegap, on the site it works with no problems, but on the device, when you try to retrieve the cookie which has a JSON, it's already an object, so if you try to JSON.parse it, it will give a JSON parse error. Solved it with an "if typeof x == 'string'" do the JSON.parse, else, just use the object. 6 goddamn hours looking for the error in all the wrong places – Andrei Cristian Prodan Jul 02 '13 at 12:13
  • 12
    when removing the cookie, make sure to also set the path to the same path as you set the cookie originally: `$.removeCookie('nameofcookie', { path: '/' });` – LessQuesar Aug 10 '13 at 00:58
  • I set cookie using. document.cookie but it is not working. http://stackoverflow.com/questions/18429234/javascript-document-cookie-not-working-with-custom-path is this plugin help?. the cookie will expire in minutes. – Jithin Jose Aug 26 '13 at 05:28
  • When including a cross-site javascript (from a sub-domain), does the path and domain default to the page, or the script's site? – Christopher Stevenson Aug 26 '13 at 17:33
  • If you can't get or set a cross-domain cookie, then what's the `domain` property you are passing for, subdomains? – Jonny May 04 '14 at 07:34
  • 32
    It's 2015 and we are still receiving more than 2k unique hits per week in jquery-cookie repository just from this answer. A couple of things we can learn from that: 1. cookies are not going to die soon and 2. People still google for a "jquery plugin to save the world". jQuery is NOT necessary for handling cookies, jquery-cookie is being renamed to js-cookie (https://github.com/js-cookie/js-cookie) and jquery dependency was made optional in version 1.5.0. There will be a version 2.0.0 with a lot of interesting stuff, it's worth take a look and contribute, thx! – Fagner Brack Apr 21 '15 at 18:06
  • @FagnerBrack Are you leaving the original project up so that people can still find it? I've added a note at the end of the answer saying that the project is being moved, but would also like to be able to say that people don't need to worry about it going away. – Alistair Evans Apr 22 '15 at 07:28
  • 2
    @Kazar We are not planning to physically move it, there is a considerable amount of overall traffic to that URL from several sources and Klaus is the historic owner of the "jquery-cookie" namespace. There's no need to worry for that URL being gone anytime soon. But still, I would encourage everyone to start watching the new repository for updates. – Fagner Brack Apr 22 '15 at 16:15
436

There is no need to use jQuery particularly to manipulate cookies.

From QuirksMode (including escaping characters)

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 = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = encodeURIComponent(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 decodeURIComponent(c.substring(nameEQ.length, c.length));
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

Take a look at

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Russ Cam
  • 117,566
  • 29
  • 193
  • 253
  • 2
    Hi Russ, the good thing about jquery cookie is that it escapes the data – Svetoslav Marinov Jan 18 '11 at 14:49
  • 2
    @lordspace - Just wrap the value in window.escape/unescape to write/retrieve the cookie value, respectively :) – Russ Cam Jan 18 '11 at 18:03
  • 47
    Better cookie code can be found here: https://developer.mozilla.org/en/DOM/document.cookie – SDC Jul 11 '12 at 14:03
  • @SDC: Would that code from mozilla work in all major browsers? – Oliver May 14 '13 at 16:11
  • @Oliver - yes it would. Nothing browser specific there. – SDC May 31 '13 at 12:59
  • JSHint complains that `expires` was already defined and `===` was not used to compare with `0` and `' '`. – Alex W Nov 26 '13 at 20:00
  • 5
    the jQuery cookie plugin is much simpler – brauliobo Jun 01 '14 at 14:28
  • 1
    instead of escape or unescape you can use encodeURI or decodeURI – Rodislav Moldovan Oct 25 '14 at 17:43
  • 1
    This solution is not going to work, `encodeURIComponent` can erroneously encode characters that are allowed in cookie-value or cookie-name according to the RFC 6265: https://github.com/js-cookie/js-cookie/pull/20#issuecomment-94453407. That can cause trouble for removing a cookie using third party solutions that expect some characters not to be encoded in the cookie-name. – Fagner Brack Apr 21 '15 at 18:05
164
<script type="text/javascript">
    function setCookie(key, value, expiry) {
        var expires = new Date();
        expires.setTime(expires.getTime() + (expiry * 24 * 60 * 60 * 1000));
        document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
    }

    function getCookie(key) {
        var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
        return keyValue ? keyValue[2] : null;
    }

    function eraseCookie(key) {
        var keyValue = getCookie(key);
        setCookie(key, keyValue, '-1');
    }

</script>

You can set the cookies as like

setCookie('test','1','1'); //(key,value,expiry in days)

You can get the cookies as like

getCookie('test');

And finally you can erase the cookies like this one

eraseCookie('test');

Hope it will helps to someone :)

EDIT:

If you want to set the cookie to all the path/page/directory then set path attribute to the cookie

function setCookie(key, value, expiry) {
        var expires = new Date();
        expires.setTime(expires.getTime() + (expiry * 24 * 60 * 60 * 1000));
        document.cookie = key + '=' + value + ';path=/' + ';expires=' + expires.toUTCString();
}

Thanks, vicky

Vignesh Pichamani
  • 7,120
  • 21
  • 68
  • 105
18

You can use a plugin available here..

https://plugins.jquery.com/cookie/

and then to write a cookie do $.cookie("test", 1);

to access the set cookie do $.cookie("test");

Divyesh Kanzariya
  • 2,881
  • 2
  • 36
  • 39
13

Here is my global module I use -

var Cookie = {   

   Create: function (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=/";
   },

   Read: function (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;
    },

    Erase: function (name) {

        Cookie.create(name, "", -1);
    }

};
seanjacob
  • 2,118
  • 1
  • 20
  • 25
10

Make sure not to do something like this:

var a = $.cookie("cart").split(",");

Then, if the cookie doesn't exist, the debugger will return some unhelpful message like ".cookie not a function".

Always declare first, then do the split after checking for null. Like this:

var a = $.cookie("cart");
if (a != null) {
    var aa = a.split(",");
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
user890332
  • 1,141
  • 12
  • 15
  • The sample code is not complete. Is it only a single `}` that is missing or are there several lines of code missing? – Peter Mortensen Jan 08 '18 at 12:59
  • It's just a singe } missing, but obviously you will need to add more lines of code to continue what you want to do with the split. – user890332 Jan 09 '18 at 18:09
9

Here is how you set the cookie with JavaScript:

below code has been taken from https://www.w3schools.com/js/js_cookies.asp

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

now you can get the cookie with below function:

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

And finally this is how you check the cookie:

function checkCookie() {
    var username = getCookie("username");
    if (username != "") {
        alert("Welcome again " + username);
    } else {
        username = prompt("Please enter your name:", "");
        if (username != "" && username != null) {
            setCookie("username", username, 365);
        }
    }
}

If you want to delete the cookie just set the expires parameter to a passed date:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
Sean Kendle
  • 2,956
  • 1
  • 21
  • 27
S1awek
  • 960
  • 8
  • 11
7

A simple example of set cookie in your browser:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>jquery.cookie Test Suite</title>

        <script src="jquery-1.9.0.min.js"></script>
        <script src="jquery.cookie.js"></script>
        <script src="JSON-js-master/json.js"></script>
        <script src="JSON-js-master/json_parse.js"></script>
        <script>
            $(function() {

               if ($.cookie('cookieStore')) {
                    var data=JSON.parse($.cookie("cookieStore"));
                    $('#name').text(data[0]);
                    $('#address').text(data[1]);
              }

              $('#submit').on('click', function(){

                    var storeData = new Array();
                    storeData[0] = $('#inputName').val();
                    storeData[1] = $('#inputAddress').val();

                    $.cookie("cookieStore", JSON.stringify(storeData));
                    var data=JSON.parse($.cookie("cookieStore"));
                    $('#name').text(data[0]);
                    $('#address').text(data[1]);
              });
            });

       </script>
    </head>
    <body>
            <label for="inputName">Name</label>
            <br /> 
            <input type="text" id="inputName">
            <br />      
            <br /> 
            <label for="inputAddress">Address</label>
            <br /> 
            <input type="text" id="inputAddress">
            <br />      
            <br />   
            <input type="submit" id="submit" value="Submit" />
            <hr>    
            <p id="name"></p>
            <br />      
            <p id="address"></p>
            <br />
            <hr>  
     </body>
</html>

Simple just copy/paste and use this code for set your cookie.

Wilq
  • 2,200
  • 4
  • 30
  • 35
Webpixstudio
  • 147
  • 2
  • 2
  • 1
    Just a note, the browser by default cache the resources according to their filenames. In this example, `jquery-1.9.0.min.js` will be reloaded for everybody when the filename is updated to `jquery-1.9.1.min.js`, otherwise the browser will NOT make a request to the server at all to check for updated content. If you update the code inside `jquery.cookie.js` without changing it's filename, then it may NOT be reloaded in browsers that already cached the `jquery.cookie.js` resource. – Fagner Brack Apr 21 '15 at 18:01
  • If you are writing a website and copying/pasting this, be aware that this is not going to work if you update `jquery.cookie.js` version without changing it's filename (unless your server deal with caching using E-Tags). – Fagner Brack Apr 21 '15 at 18:01
  • if ($.cookie('cookieStore')) { var data=JSON.parse($.cookie("cookieStore")); // when load page in different page not found $('#name').text(data[0]); $('#address').text(data[1]); } – Mohammad Javad Jun 21 '18 at 06:19
5

You can use the library on Mozilla website here

You'll be able to set and get cookies like this

docCookies.setItem(name, value);
docCookies.getItem(name);
Moustafa Samir
  • 2,113
  • 1
  • 22
  • 30
3

I think Fresher gave us nice way, but there is a mistake:

    <script type="text/javascript">
        function setCookie(key, value) {
            var expires = new Date();
            expires.setTime(expires.getTime() + (value * 24 * 60 * 60 * 1000));
            document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
        }

        function getCookie(key) {
            var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
            return keyValue ? keyValue[2] : null;
        }
   </script>

You should add "value" near getTime(); otherwise the cookie will expire immediately :)

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
barmyman
  • 63
  • 7
  • 2
    "value" could be a string. In the question he's using 1 as an example. Value should be what the key is equal to, not the length in days before the cookie expires. If value were passed in as "foo" your version would crash. – Peter Jun 03 '15 at 17:34
1

I thought Vignesh Pichamani's answer was the simplest and cleanest. Just adding to his the ability to set the number of days before expiration:

EDIT: also added 'never expires' option if no day number is set

        function setCookie(key, value, days) {
            var expires = new Date();
            if (days) {
                expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
                document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
            } else {
                document.cookie = key + '=' + value + ';expires=Fri, 30 Dec 9999 23:59:59 GMT;';
            }
        }

        function getCookie(key) {
            var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
            return keyValue ? keyValue[2] : null;
        }

Set the cookie:

setCookie('myData', 1, 30); // myData=1 for 30 days. 
setCookie('myData', 1); // myData=1 'forever' (until the year 9999) 
freeworlder
  • 1,169
  • 13
  • 19
1

I know there are many great answers. Often, I only need to read cookies and I do not want to create overhead by loading additional libraries or defining functions.

Here is how to read cookies in one line of javascript. I found the answer in Guilherme Rodrigues' blog article:

('; '+document.cookie).split('; '+key+'=').pop().split(';').shift()

This reads the cookie named key, nice, clean and simple.

Fabian
  • 541
  • 5
  • 22
1

Try (doc here, SO snippet not works so run this one)

document.cookie = "test=1"             // set
document.cookie = "test=1;max-age=0"   // unset
Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
0

The following code will remove all cookies within the current domain and all trailing subdomains (www.some.sub.domain.com, .some.sub.domain.com, .sub.domain.com and so on.).

A single line vanilla JS version (no need for jQuery):

document.cookie.replace(/(?<=^|;).+?(?=\=|;|$)/g, name => location.hostname.split('.').reverse().reduce(domain => (domain=domain.replace(/^\.?[^.]+/, ''),document.cookie=`${name}=;max-age=0;path=/;domain=${domain}`,domain), location.hostname));

This is a readable version of this single line:

document.cookie.replace(
  /(?<=^|;).+?(?=\=|;|$)/g, 
  name => location.hostname
    .split(/\.(?=[^\.]+\.)/)
    .reduceRight((acc, val, i, arr) => i ? arr[i]='.'+val+acc : (arr[i]='', arr), '')
    .map(domain => document.cookie=`${name}=;max-age=0;path=/;domain=${domain}`)
);
Slavik Meltser
  • 7,008
  • 2
  • 37
  • 37
-1
$.cookie("test", 1); //set cookie
$.cookie("test"); //get cookie
$.cookie('test', null); //delete cookie
Hasan Badshah
  • 639
  • 1
  • 6
  • 14