Create a cookie if (and only if) it doesn't already exist

Sphvn picture Sphvn · May 13, 2010 · Viewed 61.5k times · Source

I want to:

  1. Check to see if a cookie with name of "query" exists
  2. If yes, then do nothing
  3. If no, create a cookie "query" with a value of 1

Note: I am using jQuery 1.4.2 and the jQuery cookie plugin.

Does anyone have any suggestions as to how I can do this?

Answer

Jacob Relkin picture Jacob Relkin · May 13, 2010
if($.cookie('query') === null) { 
    $.cookie('query', '1', {expires:7, path:'/'});
}

Alternatively, you could write a wrapper function for this:

jQuery.lazyCookie = function() {
   if(jQuery.cookie(arguments[0]) !== null) return;
   jQuery.cookie.apply(this, arguments);
};

Then you'd only need to write this in your client code:

$.lazyCookie('query', '1', {expires:7, path:'/'});