Can jQuery read/write cookies to a browser?

casademora picture casademora · Sep 18, 2008 · Viewed 119k times · Source

Simple example: I want to have some items on a page (like divs or table rows), and I want to let the user click on them to select them. That seems easy enough in jQuery. To save which items a user clicks on with no server-side post backs, I was thinking a cookie would be a simple way to get this done.

  1. Is this assumption that a cookie is OK in this case, correct?
  2. If it is correct, does the jQuery API have some way to read/write cookie information that is nicer than the default JavaScript APIs?

Answer

adam picture adam · Feb 5, 2010

The default JavaScript "API" for setting a cookie is as easy as:

document.cookie = 'mycookie=valueOfCookie;expires=DateHere;path=/'

Use the jQuery cookie plugin like:

$.cookie('mycookie', 'valueOfCookie')