code_junkie

What is the “best” way to get and set a single cookie value using JavaScript

Nov 12th, 2011
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. function createCookie(name,value,days) {
  2. if (days) {
  3. var date = new Date();
  4. date.setTime(date.getTime()+(days*24*60*60*1000));
  5. var expires = "; expires="+date.toGMTString();
  6. }
  7. else var expires = "";
  8. document.cookie = name+"="+value+expires+"; path=/";
  9. }
  10.  
  11. function readCookie(name) {
  12. var nameEQ = name + "=";
  13. var ca = document.cookie.split(';');
  14. for(var i=0;i < ca.length;i++) {
  15. var c = ca[i];
  16. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  17. if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  18. }
  19. return null;
  20. }
  21.  
  22. function eraseCookie(name) {
  23. createCookie(name,"",-1);
  24. }
  25.  
  26. var oldCount = parseInt(readCookie('hitCount')) | 0;
  27. createCookie('hitCount', oldCount + 1, 7);
  28.  
  29. var x = "5"; // x = "5" (string)
  30. x += 1; // x = "51" (string!)
  31. x += 5; // x = "515" (string!)
  32. ++x; // x = 516 (number)
  33.  
  34. var cookieName = "increment";
  35.  
  36. if ($.cookie(cookieName) == null){
  37. $.cookie(cookieName, 1, { expires: 10 });
  38. }else{
  39. var newValue = Number($.cookie(cookieName)) + 1;
  40. $.cookie(cookieName, newValue, { expires: 10 });
  41. }
Add Comment
Please, Sign In to add comment