Posted By

brandonjp on 07/07/10


Tagged

basic javascript js textmate plugin cookie simple jquery function cookies quick easy jQ fn


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

brandonjp
Vordreller
sethetter
dop3


jsCookies - my simple easy pure js javascript cookies function


 / Published in: JavaScript
 

  1. // create my jsCookies function
  2. var jsCookies = {
  3.  
  4. // this gets a cookie and returns the cookies value, if no cookies it returns blank ""
  5. get: function(c_name) {
  6. if (document.cookie.length > 0) {
  7. var c_start = document.cookie.indexOf(c_name + "=");
  8. if (c_start != -1) {
  9. c_start = c_start + c_name.length + 1;
  10. var c_end = document.cookie.indexOf(";", c_start);
  11. if (c_end == -1) {
  12. c_end = document.cookie.length;
  13. }
  14. return unescape(document.cookie.substring(c_start, c_end));
  15. }
  16. }
  17. return "";
  18. },
  19.  
  20. // this sets a cookie with your given ("cookie name", "cookie value", "good for x days")
  21. set: function(c_name, value, expiredays) {
  22. var exdate = new Date();
  23. exdate.setDate(exdate.getDate() + expiredays);
  24. document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : "; expires=" + exdate.toUTCString());
  25. },
  26.  
  27. // this checks to see if a cookie exists, then returns true or false
  28. check: function(c_name) {
  29. c_name = jsCookies.get(c_name);
  30. if (c_name != null && c_name != "") {
  31. return true;
  32. } else {
  33. return false;
  34. }
  35. }
  36.  
  37. };
  38. // end my jsCookies function
  39.  
  40. // USAGE - get :: jsCookies.get("cookie_name_here"); [returns the value of the cookie]
  41. // USAGE - set :: jsCookies.set("cookie_name", "cookie_value", 5 ); [give name, val and # of days til expiration]
  42. // USAGE - check :: jsCookies.check("cookie_name_here"); [returns only true or false if the cookie exists or not]

Report this snippet  

You need to login to post a comment.