Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

How to use cookies in jQuery without a plugin

1.00/5 (1 vote)
14 Jul 2015CPOL2 min read 22.5K  
No muss, no fuss way to get, set, and manipulate cookie vals using jQuery

Look, Ma, no Plugins!

jQuery Plugins are great; it could even be said they are the cat's miaow, the crow's caw, or the elephant's trumpet blast. However, they have their down side, too, in complicating your code by forcing you to download and/or reference them, and possibly necessitating the care and feeding (maintainence) of more "pieces parts" that may need to be updated from time to time.

And so, here is a way to use cookies in jQuery with no muss, no fuss.

This is an obviously simplistic and contrived example, but it shows how you can get and set cookie vals, manipulate them during a session, and then reset the cookie back to zilch so that it is not carried over to the next time.

This asumes that you are incrementing a cookie val named "adumas" each time a user clicks a button named "btnAddMonteCristo"

First, here are the get and set functions, which I got from here:

C#
function setCookie(key, value) {
    var expires = new Date();
    expires.setTime(expires.getTime() + 31536000000); //1 year  
    document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
}

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

To "start fresh" each time, set the value of the cookie to 0 when unloading:

C#
$(window).unload(function () {
    setCookie('adumas', '0');
});

Retrieve the value (it should be 0) on loading:

C#
$(window).load(function () {
    var countofmontecristo = getCookie('adumas');  
});

And here's how you can set the value during operations:

C#
$(document).on("click", '[id$=btnAddMonteCristo]', function (e) {
    var currentcount = new Number(getCookie('adumas'));
    var thebettertoincyouwithmydear = new Number(1);
    currentcount = currentcount + thebettertoincyouwithmydear;
    setCookie('adumas', currentcount);
});

Of course, for this to be of any value, you need to use the value somewhere by calling getCookie and then doing something with it - displaying it or whatever. You could also decrement it, if that makes sense, in additiion to incrementing it, as shown in the example; alas, though, those things are left as an exercise for the tippler (a tippler is a reader of tips) - you, by definition, whereas a tipster is the cat (or crow or elephant) who wrote the tip. If I were Barry Manilow, I would write a song with the lines, "I wrote the tip that made the whole world tipsy..."

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)