Can jQuery read/write cookies to a browser?
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.
- Is this assumption that a cookie is OK in this case, correct?
- If it is correct, does the jQuery API have some way to read/write cookie information that is nicer than the default JavaScript APIs?
Solution 1:
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')
Solution 2:
You'll need the cookie plugin, which provides several additional signatures to the cookie function.
$.cookie('cookie_name', 'cookie_value')
stores a transient cookie (only exists within this session's scope, while $.cookie('cookie_name', 'cookie_value', 'cookie_expiration")
creates a cookie that will last across sessions - see http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/ for more information on the JQuery cookie plugin.
If you want to set cookies that are used for the entire site, you'll need to use JavaScript like this:
document.cookie = "name=value; expires=date; domain=domain; path=path; secure"