-1

I am new to JavaScript and cookies, so I have this weird question as different websites had different format. So I had confusion on how the cookies read and access the different parts of it, i.e. how do cookies recognize names from path or expiration date? Do we always have to specify "username=...;path=/;" for it to recognize it or does it automatically find it based on the format? And the main question that I am trying to figure is how I can add a value to the cookie creation code, such as a " document.cookie="username=John;visit=1;" and use that visit part to tell the hit count by adding 1 to it every time the page loads.

Thank you!

arthrax
  • 161
  • 2
  • 4
  • 12

1 Answers1

1

I use two functions (maybe the original code was from here or here) for getting and setting cookies, here are they:

function setCookie(cookieName, content, expires, path) {
  var date = new Date();
  date.setDate(date.getDate() + expires);
  var cookie = escape(content) + (expires == null ? "" : "; expires=" + date.toUTCString()) + (path != null ? "; path=" + path : "");
  document.cookie = cookieName + "=" + cookie;
  return true;
}

function getCookie(cookieName) {
  var cookie = document.cookie,
      begin = cookie.indexOf(" " + cookieName + "=");
  if (begin == -1) begin = cookie.indexOf(cookieName + "=");
  if (begin == -1) cookie = null;
  else {
    begin = cookie.indexOf("=", begin) + 1;
    var end = cookie.indexOf(";", begin);
    if (end == -1) end = cookie.length;
    cookie = unescape(cookie.substring(begin, end));
  }
  return cookie;
}

With them you can easily do what you want:

  1. Handle the page loads (eg <body onload="pageLoad()">)
  2. Add a script element to the head part of the page, and the two funtions above
  3. Add the following function inside the script element:
    function pageLoad() { var cCont = getCookie('hitCount'); var count = 0; if (cCont != null) count = parseInt(count + ''); setCookie('hitCount', (count + 1) + '', null, null); }
  4. If you want to get the hit count, you can use the count variable, or use the getCookie function again.


Your first question is not totally clear to me, but read this page, there are nice examples and code samples. This is another good presentation of cookies.

Community
  • 1
  • 1
nvi9
  • 1,733
  • 2
  • 15
  • 20