Roch
Roch

Reputation: 22041

Managing cookies with Javascript

I have tried to create a popup manager using Javascript, the idea is to display the ajax popup only once. For some reason the popup appears more than once and randomly. I would like to know if there is something wrong with my code:

 function SetCookie(name, value, days) {
     var expire = new Date ();
     expire.setTime (expire.getTime() + (24 * 60 * 60 * 1000) * days);
     document.cookie = name + "=" + escape(value) + "; expires=" +expire.toGMTString();
 }
 function GetCookie(name) {
   var startIndex = document.cookie.indexOf(name);
  if (startIndex != -1) {
      var endIndex = document.cookie.indexOf(";", startIndex);
      if (endIndex == -1) endIndex = document.cookie.length;
      return unescape(document.cookie.substring(startIndex+name.length+1, endIndex));
  }
  else {
      return null;
  }
 }

function DeleteCookie(name) {
    var expire = new Date ();
    expire.setTime (expire.getTime() - (24 * 60 * 60 * 1000));
    document.cookie = name + "=; expires=" + expire.toGMTString();
}

 function Pop() {
    var cookie = GetCookie("popup");
    if(cookie==null) {
        SetCookie("popup",1,300);
 }
    else {
        if(cookie==1) {
            new Ajx.Dialog();
            SetCookie("popup",2,300);
            return false;
        }
        else {
            return false;
        }
    }
  }
  window.onload = Pop;

Upvotes: 0

Views: 1473

Answers (1)

johnhunter
johnhunter

Reputation: 1836

Ok, so what is happening is this:

function Pop() {
    var cookie = GetCookie("popup");
    if(cookie==null) {
        SetCookie("popup",1,300);
    }
    else {
        if(cookie==1) { 
            new Ajx.Dialog();
            SetCookie("popup",2,300);
            return false;
        }
        else {
            return false;
        }
    }
}
  1. First visit and cookie is null. Cookie is set to 1 and pop function exits.
  2. Second visit and cookie is 1. Ajx.Dialog called, cookie set to 2, pop function returns false.
  3. Third visit and cookie is 2. pop function returns false.

Is this what you intended?

UPDATE:

I'm not sure what you want to happen, but if you want the popup to fire once on first visit then use the following:

function Pop() {
    var cookie = GetCookie("popup");
    if(cookie != 1) {
        new Ajx.Dialog();
        SetCookie("popup", 1, 300);
    }
}

Upvotes: 1

Related Questions