Click here to Skip to main content
15,886,137 members
Articles / Programming Languages / Javascript
Tip/Trick

How to use cookies in jQuery without a plugin

Rate me:
Please Sign up or sign in to vote.
1.00/5 (1 vote)
14 Jul 2015CPOL2 min read 21.4K   2  
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)


Written By
Founder Across Time & Space
United States United States
I am in the process of morphing from a software developer into a portrayer of Mark Twain. My monologue (or one-man play, entitled "The Adventures of Mark Twain: As Told By Himself" and set in 1896) features Twain giving an overview of his life up till then. The performance includes the relating of interesting experiences and humorous anecdotes from Twain's boyhood and youth, his time as a riverboat pilot, his wild and woolly adventures in the Territory of Nevada and California, and experiences as a writer and world traveler, including recollections of meetings with many of the famous and powerful of the 19th century - royalty, business magnates, fellow authors, as well as intimate glimpses into his home life (his parents, siblings, wife, and children).

Peripatetic and picaresque, I have lived in eight states; specifically, besides my native California (where I was born and where I now again reside) in chronological order: New York, Montana, Alaska, Oklahoma, Wisconsin, Idaho, and Missouri.

I am also a writer of both fiction (for which I use a nom de plume, "Blackbird Crow Raven", as a nod to my Native American heritage - I am "½ Cowboy, ½ Indian") and nonfiction, including a two-volume social and cultural history of the U.S. which covers important events from 1620-2006: http://www.lulu.com/spotlight/blackbirdcraven

Comments and Discussions

 
-- There are no messages in this forum --