Learning Learning - 1 year ago 99
Javascript Question

Check if cookie exists else set cookie to Expire in 10 days

Here is what I'm looking to do (pseudo-code):

Imagine the name of the cookie in the example is "visited" and it contains nothing.

if visited exists
then alert("hello again");
create visited - should expire in 10 days;
alert("This is your first time!")

How can I achieve this in JavaScript?

Answer Source

You need to read and write document.cookie

if (document.cookie.indexOf("visited") >= 0) {
  // They've been here before.
  alert("hello again");
else {
  // set a new cookie
  expiry = new Date();
  expiry.setTime(expiry.getTime()+(10*60*1000)); // Ten minutes

  // Date()'s toGMTSting() method will format the date correctly for a cookie
  document.cookie = "visited=yes; expires=" + expiry.toGMTString();
  alert("this is your first time");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download