0

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;
1
  • 2
    Based on the code you provided you don't appear to have defined a SetCookie function. Commented Mar 9, 2011 at 11:40

1 Answer 1

1

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);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer, yes my idea is to display the popup only on the second pageview
OK. I found your pop function worked as you expected on Firefox 3.6 and see no reason why it wouldn't work on other browsers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.