|
Documentation
How to use jquery.cookies.js
Featured How to use jquery.cookies.js
Without jQueryIf jQuery is not available in your page, the core cookies library is available to you under the jaaulde.utils namespace: Get a cookie/** * get - get one, several, or all cookies * * @access public * @paramater Mixed cookieName - String:name of single cookie; Array:list of multiple cookie names; Void (no param):if you want all cookies * @return Mixed - Value of cookie as set; Null:if only one cookie is requested and is not found; Object:hash of multiple or all cookies (if multiple or all requested); */ get = function(cookieName) Example:
Get Filtered list of cookies/** * filter - get array of cookies whose names match the provided RegExp * * @access public * @paramater Object RegExp - The regular expression to match against cookie names * @return Mixed - Object:hash of cookies whose names match the RegExp */ filter = function( cookieNameRegExp ) Example:
Set a cookie/** * set - set or delete a cookie with desired options * * @access public * @paramater String cookieName - name of cookie to set * @paramater Mixed value - Any JS value. If not a string, will be JSON encoded (http://code.google.com/p/cookies/wiki/JSON); NULL to delete * @paramater Object options - optional list of cookie options to specify * @return void */ set = function(cookieName, value, options) Example:
Delete a cookie/** * del - delete a cookie (domain and path options must match those with which the cookie was set; this is really an alias for set() with parameters simplified for this use) * * @access public * @paramater MIxed cookieName - String name of cookie to delete, or Bool true to delete all * @paramater Object options - optional list of cookie options to specify ( path, domain ) * @return void */ del = function(cookieName, options) Example:
Test if browser is accepting cookies/** * test - test whether the browser is accepting cookies * * @access public * @return Boolean */ test = function() Example:
Set default options to use when none are specified/** * setOptions - set default options for calls to cookie methods * * @access public * @param Object options - list of cookie options to specify * @return void */ setOptions = function(options) Example:
With jQueryIf jQuery is available, then all of the above methods are available to you under the jQuery.cookies (or $.cookies ) namespace:
In addition, there are some jQuery function additions for helping automate some cookie tasks:
Options objectUsing the options object, cookies can be set with several options such as the domain and or path for which the cookie should be available, expiration date for the cookie, and whether the cookie should be sent over HTTPS only. The options object has four properties:
The structure of the object is as follows: var newOptions = {
domain: '*.mydomain.com',
path: '/somedir',
expiresAt: new Date( 2011, 1, 1 ),
secure: true
}You need only set those options which you desire to override. The default options when not overridden are:
An options object can be passed with set(), del(), cookify(), and cookieBind() to override the defaults on a case by case basis. You can also pass an options object to setOptions() to override the defaults for all calls. IMPORTANT NOTE: Cookies must be deleted using the same domain and path options with which they were set. Else the cookie will not delete. This is just how cookies work. |
First off, thanks for this great jQuery plugin.
Second, thank you for avoiding puns when you mention that "This is just how cookies work." ;)
Cheers!
How do you set the expiration date? How should that be formatted?
Thanks for this plugin.
But I got a problem. When I use chinese word in cookies. I got the cookie, but can't show the chinese word currectly. I use decodeURI to replace with the unescape to solve this problem.
xxfflower@qq.com
@all Sorry to have ignored the older comments and issues. I was not monitoring this page very closely as I assumed Google Code would email me when comments, issues, etc were left. I'll be watching more closely now.
@cmtonkinson - thank for the comments!
@doug.bonneville - I support expiration via the hoursToLive option. You just tell the library how many hours the cookie should be valid and it will produce the expiration time stamp
@xizhonghua - do you mind opening an issue for me on that? In that issue can you show me the code you used to fix the problem you're having? Thanks a lot!
I hope to have a patched version out soon with the small fixes for reported issues thus far.
Hi, first off, thank you for writing this plugin. It makes cookies much easier and faster to work with if you're using jQuery. I don't know why jQuery doesn't have this built in...MooTools? does. But, anyway, are there any issues with this plugin and jQuery 1.3.x ? I can't seem to get it to work.
@digitalmatthew I have done some limited testing with 1.3.1 and had no problems as of yet. I am working on releasing 2.0.1 of this library with a few fixes and hope to do full testing with jQ 1.3.1. I'd love it if you would open issues ( http://code.google.com/p/cookies/issues/list ) on the specific problems you're facing so that I know where to target some testing.
Thanks, Jim
Just wanted to drop a note and let you know that this documentation saved me hours of work! thank you for the clear descriptions and ease of use. Marie
Great plugin! Thanks for sharing it with all of us! I made a slight modification to enable cookieBind() with <select> elements also:
In cookieFill() replace the nodeType check with this:
if (nodeType === 'input' || nodeType === 'textarea' || nodeType === 'select') { $(this).val(value); }@docpommes that sounds great. I had written then method hastily and meant to get back to it to better support other things. I'll put in an Enhancement request on the Issues list and try to work this into 2.0.2.
@everyone How can i implements this code in a website? Is there are a sample of implementation code? Which vars i need to replace?
Thanks.
@tony.rodz5 you do not need to replace any of the options unless you have a specific need in mind. The most common one replaced is hoursToLive as different cookies often need different expire times. As for how to implement, it depends on exactly what you're wanting to do.
@auldridgej So, i put the js within <head> and change the hoursToLive and that is it? Got it! Thank you. ;-)
@tony.rodz5 well, yes, that's a start. Each option can be changed per cookie set(), or can be set globally via setOptions().
I can't seem to set a cookie when using custom options. Works fine if I don't try to override the options. I'm using jQuery 1.3.2.
Please open an issue and provide detailed information on which options you're attempting to override.
Thanks, Jim
@auldridgej Is there an option where jquery bind to cookie changes. tq
Couldn't get cookie.get to work and realized there is a limitation in IE with document.cookie if over 4096 bytes of cookies stored. Deleted some cookies and everything is great.
@hudzaifah - if you mean a way to have a cookie be stored under a different name than the ID/Name of the input to which you're binding it, I have not adding anything like that.
@hammo...@yahoo.com Thanks for the note!
Is there anyway to have the cookie expire on browser close and time based? which ever comes first?
@Peter.wolk no cookies do not have this functionality (AFAIK).
Thanks for the quick response! Another question, I can't seem to get a cookie that i know is on my machine. the page that's calling this code in on another domain but i don't believe that should matter since it should just be searching for the cookie on my machine.
var cookie_value = $.cookies.get('test_info', {domain: 'www.test.com', path : '/'});I'm i doing this incorrectly?
@Peter.wolk when retrieving cookies, only the name of the desired cookie can be passed in. Cookie technology limits read to those cookies which have not expired, and were originally set for the current path/domain.
@my earlier comment: if anyone is interested in doing something when the session ends or time end, whichever comes first:
$('#acpt').click(function () { $.cookies.set('ses', 'full_acpt', {path : '/'}); $.cookies.set('sxmns', 'full_acpt', {path : '/', hoursToLive: .1}); }); var cookie_value_ses = $.cookies.get('ses', {path : '/'}); var cookie_value_sxmns = $.cookies.get('sxmns', {path : '/'}); if(cookie_value_ses != "full_acpt") { //do something }else if(cookie_value_sxmns != "full_acpt"){ //do something }@Peter.wolk good work and thanks for sharing!
Hello, this is the code I tried for supporting checkboxes and radio buttons.
Index: jquery.cookies.2.1.0.js =================================================================== --- jquery.cookies.2.1.0.js (revision 56) +++ jquery.cookies.2.1.0.js (working copy) @@ -321,16 +321,18 @@ { inputType = inputType.toLowerCase(); } - if( inputType !== 'radio' && inputType !== 'checkbox' ) + resolvedValue = true; + if( inputType === 'radio' || inputType === 'checkbox' ) { + value = $( this ).attr("checked"); + } else { value = $( this ).val(); - resolvedValue = true; } } if( resolvedValue ) { - if( typeof value !== 'string' || value === '' ) + if( value === '' || value === false) { value = null; } @@ -372,7 +374,13 @@ nodeName = this.nodeName.toLowerCase(); if( nodeName === 'input' || nodeName === 'textarea' || nodeName === 'select' ) { - $( this ).val( value ); + inputType = $( this ).attr( 'type' ); + + if ( inputType === 'checkbox' || inputType === 'radio' ) { + $( this ).attr({checked: true}); + } else { + $( this ).val( value ); + } } else {@michele.costabile issue #12 opened as an enhancement request
Wow! Thanks! Works like a charm, is so simple to use and is very well documented! Thanks for sharing!
hi, i wanted a javascript to automatically read the cookies, get the domain name from them and eliminate the duplicates, which i hav to store in the database, i am doing this project on Microsoft visual studio 2008. Could you please help me with it ?
Hello gururajjs,
I think you may misunderstand how cookies work. From the point of view of client code, cookies can be set to a particular path and/or domain with an expiration and a secure flag. However, when reading, the script is only given access to a name/value list of unexpired cookies which were set to the current domain/path. Also, cookies set by the same name to the same domain/path do not duplicate--they are overwritten. The last call to write the cookie wins.
I hope this helps, but feel free to ask questions. Jim
Hi,
Thanks a lot for this fantastic plugin. ^^
Just an enhancement suggestion. Can we expose a function to call for plugging into the jQuery namespace? This is useful in the situation that the cookie library is needed before jQuery loads, and we do not want to reload the library to just to get the plugging done.
Perhaps
( function() {
. . . } )();This will allow us to call jaaulde.utils.cookies.jQueryBind( window.jQuery ) at a later stage.
Lovely little bit of code. If I can make a suggestion, perhaps you can extend the get() method to take a second parameter which is a default value to return if the get fetches nothing as the cookie isn't set. very useful for when a page first gets landed on.
Thanks for sharing
@liyang.tan: Thanks very much for your comments and suggestion. I can see your reason for asking for this, but am debating whether I should go for it. Cookie access could definitely be required very early in page loading so I understand why you might want to include it early and bind to jQ later. However, I am always trying to avoid bloat. Give me some time to consider it.
@ashley -AT- bbcb -dot- co -dot- uk: Thank you for your comments and your suggestion too. I can see some value in what it is you desire, but I think that can be done pretty easily with your own code so I am not sure whether I should add to the size of the library to accommodate.
Thanks again to you both, Jim
Did I read correctly that jquery 1.3.2 already has cookie functionality built in? I have a popup that when closed ..the cookie that was created with the launch of the popup needs to expire after 15 minutes of being opened. The popup wouldn't display again until those 15 minutes have expired.
@josephrav - No version of the jQuery API has cookie support built in. I believe the UI team was looking at building it in, but they have not done it yet either. To accomplish what you want, I would check for the presence of your cookie which holds the flag telling you the popup has displayed. If the cookie is not present, display the popup and set the cookie with an expiration date 15 minutes in the future. It's as simple as that.
Thanks @auldridgej. So I should use the jquery.cookie.js library here as an addon to my existing 1.3.2 framework? I noticed there was an issue with it. Is there a jquery.cookie.js version that works with 1.3.2.min?
@josephrav - yes, you would use my library (or another) to provide the functionality. There are some fairly minor issues as well as some enhancement requests opened on this plugin. None of those, however, have to do with basic cookie functionality--they're related to the tie-ins to DOM scripting I added. You wouldn't run into them based on what you were looking to do.
One more question...I have an alert that pops up when the page loads if no cookie is set. SInce nothing is clicked...can I change .click function to .load function...or is that even possible. The code that produces the alert on load is:
$("#alert").overlay({top:'25%',left:350, expose: {color: '#ffffff',loadSpeed: 0,opacity: 0.5},closeOnClick: false,api: true }).load();
I don't want that to happen if the cookie is set.
@josephrav I would do something like this:
$( function() { var AlertShownCookieName = 'AlertShown', AlertShownCookieExpires; if( $.cookies.get( AlertShownCookieName ) === null ) { $( '#alert' ).overlay( { top: '25%', left: 350, expose: { color: '#ffffff', loadSpeed: 0, opacity: 0.5 }, closeOnClick: false, api: true } ); AlertShownCookieExpires = new Date(); AlertShownCookieExpires.setTime( AlertShownCookieExpires.getTime() + ( 1000 * 60 * 15 ) ); $.cookies.set( AlertShownCookieName, '1', { expiresAt: AlertShownCookieExpires } ); } } );Thanks auldridgej,dowe need to leave the .load off at the end of the alert script?
@josephrav Sorry for that--you can have load() on there. I didn't have your code in context and dropped it.
Perfect...this works great...thanks so much for your help.
@josephrav No problem, I'm glad you find it useful!
I am having some issues with this plugin. Maybe a trite example but i want to save form input values in cookies.
I have multiple HTML input fields for different customers which look like this:
<select id="titleDepend1" class="inlineSpace jTitle"> <option value="Please select">Please select...</option> <option value="Mr">Mr</option> <option value="Mrs">Mrs</option> <option value="Ms">Ms</option> <option value="Miss">Miss</option> <option value="Dr">Dr</option> <option value="Other">Other</option> </select> <label for="otherDepend1" class="inlineSpace jOther">Other</label> <input type="text" class="text jOther" name="otherDepend1" id="otherDepend1" maxlength="6" />I then use jQuery to set the cookies like so:
// hide 'Other' inputs to start $('.jOther').hide(); // event listener on all select drop downs with class of jTitle $(".jTitle").change(function(){ //set the select value var val = $(this).val(); if(val != "Other") { //$(this).nextAll('.jOther').hide(); $(this).parent().find(".jOther").hide(); } else { //$(this).nextAll('.jOther').show(); $(this).parent().find(".jOther").show(); } // Sets a cookie with named after the title field's ID attribute $(this).cookify(); }); Then i loop over all the Title drop downs on the page: {{{ $(".jTitle").each(function(){ // get the id of each Title select drop down var $titleId = $(this).attr('id'); // get the value of the cookie for each cookie created above in $(this).cookify() var $cookieValue = $.cookies.get($titleId); // if value is 'Other' make sure it is shown on page refresh if ($cookieValue == 'Other') { // Show the other input $(this).parent().find(".jOther").show(); // set select value to 'Other' $(this).val('Other'); } else { // set to whatever is in the cookie $(this).val($cookieValue); } }); However, if no cookie has been set i.e. the user has just come to the page then the value of the drop down is null. I need it to be 'Please select'. }}}@ryan.pays - I have a Cub Scout meeting to lead this evening, but I will take a look at your code and see what I can do. Please give me a day or so. Thanks, Jim
The following sorts it:
$(".jTitle").each(function(){ var $titleId = $(this).attr('id'); var $cookieValue = $.cookies.get($titleId); if ($cookieValue == 'Other') { $(this).parent().find(".jOther").show(); $(this).val('Other'); } else if($cookieValue) { $(this).val($cookieValue); } }); Courtesy of Stack Overflow: http://stackoverflow.com/questions/2358689/jquery-cookies-setting-select-drop-down-value-after-page-refresh Cheers anyway :)Hi,
How do i delete all cookies with a specific value?
Also i would like to delete all cookies that have a prefix?
Cheers,
Ryan
@ryan.pays
//How do i delete all cookies with a specific value? var valueToDelete, allCookies, name; valueToDelete = 'the value'; allCookies = $.cookies.get(); if( typeof allCookies === 'object' && allCookies instanceof Array ) { for( name in allCookies ) { if( allCookies[name] === valueToDelete ) { $.cookies.del( name ); } } } //Also i would like to delete all cookies that have a prefix? var filteredCookies, name; filteredCookies = $.cookies.filter( /^site/ ); if( typeof filteredCookies === 'object' && filteredCookies instanceof Array ) { for( name in filteredCookies ) { $.cookies.del( name ); } }Please show us some samples with both code and html
@vera.waage, I'm not sure what you want to see...cookie interaction doesn't involve a lot of HTML save for the form binding methods I added to jQuery.fn. Is that what you're wanting to see?
Hi,
I'm writing a function to delete all the cookies I used and I reference your comment on Mar 11, 2010. It doesn't work.
I checked my function and your plugin and find that the "returnValue" in "filter" is not an "Array"!
I modify the declaration in filter() in jquery.cookies.2.2.0.js from "{}" to "\[\]". It's working now.
I think my solution may not be the best. Could you please give me some tips on the solution without modifying your plugin?
Dear admin,
What codes can be written?
If any of all subdirectories from Directory Root are modified the cookies. All the cookies value of all directory are changed to that cookie.
I am using Joomla, rewrite, directory structure is various and dynamic.
Thank you.
Why does filter returns an object, and not an array? o.O
@Kurtextrem - it's returning a "hash" object...keys are the names of matched cookies, values are the value of the cookie
And the get() returns an object, too, not an array ...
@Kurtextrem - correct, get(), when called to retrieve all cookies, returns the same sort of "has" object. Can you explain why this is a problem for you? Is there something you'd prefer?
@auldridgej: For me it would be better, if it would return an Array..... it's easier to become the length. In the Object length doesnt work and i have no idea to become the length of the object :/ If you can show me an exmaple i maybe understand it
Thank you for this plugin!
However I got a problem when using Chrome and slashes.
When I first cookify "1/1/1980" and then do a cookieFill Chrome preforms some maths... I think the problem has to do with json in "parseCookies" Everything works fine in Firefox and IE.
Example at http://katmo.net/cookietest/test.html
Thank you
@ivar.katmo - I have not worked much with Chrome yet so I have not seen this. I will take a look as soon as I can. Would you mind heading to http://code.google.com/p/cookies/issues/list and opening an issue to remind me to get to it?
Thanks, Jim
Thank you. Issue opened.
The example to set the domain option says: domain: "*.mydomain.com". This does not work (Firefox). If you want to set the cookie for all your subdomains, just ommit the "*". --> domain: ".mydomain.com"
$.cookies.del('my_cookie'); -> Not function.
I used $.cookies.test('my_cookie') after and it exists cookies.
Help me, please.
@cinefilo - .test() does not take any parameters and is not for testing if a particular cookie exists. This method simply tests if the browser is accepting cookies. Basically, your param is being ignored and the method is returning true letting you know the bowser is accepting cookies.
If you want to know if a cookie exists, run .get() and check if its return--null means a cookie is not set.
When i do : $.cookie.get('mycookie'); if the cookie doesnt exist, javascript breaks and firebug displays "Break on error JSON.parse".
Anyone knows this issue?
Hey, when you do a $().cookieBind(), it sets the element to the cookie value, and monitors for change. That's expected behaviour, but it would be nice to have an option to do the inverse (kinda): e.g. $().cookieBind(true) would set a cookie from the element (i.e. $().cookify()), then monitor. Currently you can do that using code in the page, but it would be useful built-in.
Also, this may be just me, but $().cookify() seems not to set a cookie if it has not been created previously, so I have to do:
$.cookies.set('my_value', ''); $('#my_value').cookify();Why's that?
I got "Break on error JSON.parse" too when the cookie didn't exist. I hadn't made changes to my code since it was last working. So I suspect the issue appeared as a result of an update to firebug or firefox. The issue is that firebug breaks after a 'try' clause throws an error. The 'try' clause in the cookies.get method calls (line 126) JSON.parse. If an error is thrown a value is set. So the code seems to work as intended.
I tried a few things that seemed to fix the issue but it happened again. The last thing I tried that seemed to work is reseting firebug options (Tools->Firebug->Options->Reset All Firebug Options).
@jack.alves thanks a lot for the info. I have not seen such an issue with Firebug, but it doesn't surprise me. I appreciate you brining it to my attention as I'm sure it will be helpful to others.
Jim
Can you give me a simple example how I can use it in Greasemonkey?
I use the following script to add checkbox to the current page:
do_modify_html_it(
and I try to keep the state of all checkboxes on the page when the page is refreshed.
Thanks,
Artug
Hi. I'm not so expert in jQuery and I ask you for help.
I want to show an overlay advertising in homepage when the home is loaded but only once per session.
Now I have this code to display my overlay:
$(document).ready(function(loadPopup) {
How can I use the cookies plugin to avoid displaying the overlay more than once per session?
Every help is welcome.
Thanks.
Fortarrigo
Would the cookied named foo not be deleted if the jaaulde.utils.cookies.del("foo", {path: "/path", expiresAt: new Date(half_an_hour_from_current_time_in_milliseconds)});?.
Say the the above code in a javascript could not run because the user logged out of his account? Would the cookie not be deleted in that case from browser even after expiration time?
@my previous comment If the cookie doesn't get deleted from the browser even after its expiration, when tried to get it back with .get() it returns a null.
I can't seem to be able to set the expiration for the cookie set using .cookieBind().
The code I am using for it is $('input[id^="_val"]').cookieBind({path: '/path', expiresAt: new Date(new Date().getTime())});.
It sets only the path but not the expiration time for the bound cookie with the input field.
How do I set expiration time to the bound cookies?
this is one awesome script if one modifies it correctly. because it seems when using cookieBind(), all inputs are identified by their name, not id. which just doesn't work for checkboxes.
i've adjusted it to save the cookies for each id and now i can even use $('input').cookieBind(); for my form with fields and checkboxes. which is ridiculously elegant and i'm enormously happy that it works.
you can get my modified version here (don't know much about this whole google system, so i don't know where i could upload the file. so i went with mediafire...): http://www.mediafire.com/?944c09jotuzcuyf