I'm trying to have a div display on the very first time a user visits my site. I'm pretty sure I do this by using cookies, which I have limited experience with and am have a hard time understanding. Most tutorials I've found online only talk about having cookies prompt a user to input something like a name, and have it recall it later, which not what I want at all. I simply want the cookie to check if the user has been to my site before, and if not, display a div that is normally hidden.
Here's something I've tried and failed to get to 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 really relevant since this works fine):
#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 content of scripts.js:
function popbox3() {
$('#overbox3').toggle();
}
And what I assume 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;
}
From my understanding, the cookie is supposed to be calling the function popbox3() only if the user has not visited, which would toggle the display of the hidden div. But as of now, nothing is working. Any clarification or help here would be greatly appreciated. Thanks in advance.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…