...

View Full Version : Check cookie value then display image



chaotic_001
01-14-2012, 11:59 AM
Hello everyone. I am trying to put together a browser based game which uses javascript and cookies, and am looking for help with one of it's functions.

I need a script which checks a cookie value, then displays a certain image, depending on what that value is. So, if the value is 50, it displays one, if it's 60 it display another one etc.

What script would I use?

xelawho
01-14-2012, 04:14 PM
a simple example - googling will get you lots of info about cookies...



<html>
<head>
<script type="text/javascript">



function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

function checkCookie()
{
var number=getCookie("number");
if (number!=null && number!="")
{
showPic(number)
}
else
{
number=prompt("Please enter a number:","");
if (number!=null && number!="")
{
setCookie("number",number,365);
showPic(number)
}
}
}

function deleteCookie(the_cookie) {
document.cookie = encodeURIComponent(the_cookie) + "=deleted; expires=" + new Date(0).toUTCString();
}

function showPic(thenum){
document.getElementById("thepic").src=thenum+".jpg"
}
</script>
</head>
<body onload="checkCookie()">
<img src="" id="thepic" onerror="alert('we have no image on file with that name'); deleteCookie('number'); checkCookie()">
</body>
</html>

Philip M
01-14-2012, 04:59 PM
Don't forget that users may (and often do) delete their cookies.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum