Cookies - set, get, delete


/ Published in: jQuery
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <html>
  2. <head>
  3. <title>jquery cookie</title>
  4.  
  5. <script type="text/javascript" src="jquery-1.2.1.min.js"></script>
  6. <script type="text/javascript" src="jquery.cookie.js"></script>
  7.  
  8. <script type="text/javascript">
  9.  
  10. $(function($) {
  11.  
  12. function displayMessage(msg) {
  13. $('#message').html(msg).css({color: 'green'});
  14. }
  15.  
  16. displayMessage('jQuery cookie plugin test');
  17.  
  18. $('#setSessionCookie').click(function() {
  19. $.cookie('test', 'Hmmm, cookie');
  20. displayMessage("Cookie 'test' has been set.");
  21. });
  22.  
  23. $('#setCookie').click(function() {
  24. $.cookie('test', 'Hmmm, cookie', { expires: 7 });
  25. displayMessage("Cookie 'test' has been set and will expire in 7 days.");
  26. });
  27.  
  28. $('#getCookie').click(function() {
  29. displayMessage("The value of the cookie named 'test' is: " + $.cookie('test'));
  30. });
  31.  
  32. $('#deleteCookie').click(function() {
  33. $.cookie('test', null);
  34. displayMessage("Cookie 'test' has been deleted.");
  35. });
  36.  
  37. $('#testCookiesEnabled').click(function() {
  38. $.cookie('testcookiesenabled', null);
  39. $.cookie('testcookiesenabled', 'enabled');
  40. if ($.cookie('testcookiesenabled')) {
  41. displayMessage("Cookie: "+ $.cookie('testcookiesenabled'));
  42. } else {
  43. displayMessage("Cookies disabled");
  44. $.cookie('testcookiesenabled', null);
  45. }
  46. });
  47.  
  48. });
  49.  
  50. </script>
  51.  
  52. </head>
  53.  
  54. <body>
  55.  
  56. <p><span id="message" style="forecolor: red;"></span>
  57.  
  58. <p><input type="button" id="testCookiesEnabled" value="Cookies enabled?"/></p>
  59.  
  60. <p><input type="button" id="setSessionCookie" value="Set session cookie"/></p>
  61.  
  62. <p><input type="button" id="setCookie" value="Set cookie expires in 7 days"/></p>
  63.  
  64. <p><input type="button" id="getCookie" value="Show cookie value"/></p>
  65.  
  66. <p><input type="button" id="deleteCookie" value="Delete the cookie"/></p>
  67.  
  68. </body>
  69. </html>
  70.  
  71.  
  72. jquery.cookie.js -
  73.  
  74. /**
  75. * Cookie plugin
  76. *
  77. * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
  78. * Dual licensed under the MIT and GPL licenses:
  79. * http://www.opensource.org/licenses/mit-license.php
  80. * http://www.gnu.org/licenses/gpl.html
  81. *
  82. */
  83.  
  84. /**
  85. * Create a cookie with the given name and value and other optional parameters.
  86. *
  87. * @example $.cookie('the_cookie', 'the_value');
  88. * @desc Set the value of a cookie.
  89. * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
  90. * @desc Create a cookie with all available options.
  91. * @example $.cookie('the_cookie', 'the_value');
  92. * @desc Create a session cookie.
  93. * @example $.cookie('the_cookie', null);
  94. * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
  95. * used when the cookie was set.
  96. *
  97. * @param String name The name of the cookie.
  98. * @param String value The value of the cookie.
  99. * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
  100. * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
  101. * If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
  102. * If set to null or omitted, the cookie will be a session cookie and will not be retained
  103. * when the the browser exits.
  104. * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
  105. * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
  106. * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
  107. * require a secure protocol (like HTTPS).
  108. * @type undefined
  109. *
  110. * @name $.cookie
  111. * @cat Plugins/Cookie
  112. * @author Klaus Hartl/[email protected]
  113. */
  114.  
  115. /**
  116. * Get the value of a cookie with the given name.
  117. *
  118. * @example $.cookie('the_cookie');
  119. * @desc Get the value of a cookie.
  120. *
  121. * @param String name The name of the cookie.
  122. * @return The value of the cookie.
  123. * @type String
  124. *
  125. * @name $.cookie
  126. * @cat Plugins/Cookie
  127. * @author Klaus Hartl/[email protected]
  128. */
  129. jQuery.cookie = function (name, value, options) {
  130. if (typeof value != 'undefined') { // name and value given, set cookie
  131. options = options || {};
  132. if (value === null) {
  133. value = '';
  134. options.expires = -1;
  135. }
  136. var expires = '';
  137. if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
  138. var date;
  139. if (typeof options.expires == 'number') {
  140. date = new Date();
  141. date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
  142. } else {
  143. date = options.expires;
  144. }
  145. expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
  146. }
  147. // CAUTION: Needed to parenthesize options.path and options.domain
  148. // in the following expressions, otherwise they evaluate to undefined
  149. // in the packed version for some reason...
  150. var path = options.path ? '; path=' + (options.path) : '';
  151. var domain = options.domain ? '; domain=' + (options.domain) : '';
  152. var secure = options.secure ? '; secure' : '';
  153. document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
  154. } else { // only name given, get cookie
  155. var cookieValue = null;
  156. if (document.cookie && document.cookie != '') {
  157. var cookies = document.cookie.split(';');
  158. for (var i = 0; i < cookies.length; i++) {
  159. var cookie = jQuery.trim(cookies[i]);
  160. // Does this cookie string begin with the name we want?
  161. if (cookie.substring(0, name.length + 1) == (name + '=')) {
  162. cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
  163. break;
  164. }
  165. }
  166. }
  167. return cookieValue;
  168. }
  169. };

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.