ONLY when displaying a div only on the first visit (cookies?)

I am trying to display a div the first time a user visits my site. I am sure that I am doing this using cookies, with which I have limited experience, and I can hardly understand. Most of the tutorials I found on the Internet only say that they have cookies so that the user enters something like a name, and remember later that it’s not at all what I want. I just want the cookie to check if the user was previously on my site, and if not, displays a div, which is usually hidden.

Here I tried something and could not work.

HTML:

<head> <script type="text/javascript" src="annoy.js"></script> <script type="text/javascript" src="scripts.js"></script> </head> ... <body> <div id="overbox3"> <div id="infobox3"> <p>This is the cookie box</p> <br /> <p>it should only show once </p> <br/><br/> </div><!-- end infobox3 --> </div> <!-- end overbox3 --> </body> 

CSS (not very important, as this works great):

 #overbox3 { position: fixed; top: 0px; left: 0px; width: 100%; height: 100%; background: rgba(64, 64, 64, 0.5); z-index: 999999; display: none; } #infobox3 { margin: auto; position: absolute; left: 35%; top: 20%; height: 300px; width: 400px; background-color: white; border: 1px solid red; } 

Relevant contents of scripts.js:

 function popbox3() { $('#overbox3').toggle(); } 

And what I suppose is the problem, the content of annoy.js:

  function GetCookie(name) { var arg=name+"="; var alen=arg.length; var clen=document.cookie.length; var i=0; while (i<clen) { var j=i+alen; if (document.cookie.substring(i,j)==arg) return "here"; i=document.cookie.indexOf(" ",i)+1; if (i==0) break; } return null; } var visit=GetCookie("COOKIE1"); if (visit==null){ var expire=new Date(); popbox3(); expire=new Date(expire.getTime()+7776000000); document.cookie="COOKIE1=here; expires="+expire; } 

In my opinion, a cookie should call the popbox3 () function only if the user has not visited to switch the display of the hidden div. But at the moment, nothing works. Any clarifications or help here would be greatly appreciated. Thanks in advance.

+4
source share
1 answer

Your cookie code looks great. You need to run it in the document handler so that it waits for the document to load before switching the DIV:

 $(function() { var visit=GetCookie("COOKIE1"); if (visit==null){ popbox3(); } var expire=new Date(); expire=new Date(expire.getTime()+7776000000); document.cookie="COOKIE1=here; expires="+expire; } 

I also made the cookie setting unconditional, so that every visit to the site will return the expiration time.

+6
source

All Articles