JavaScript cookies to make different image display? help!!?

Maggarama

New Member
I've been working on this for hours and I'm just lost.
I need for it to display a random image, but a different one each time the page loads. Here's what I have. All I want to know is if I'm even on the right track. I'm about to give up.

<html>
<head>

<script type="text/javascript">

var images = new Array("images/pic1.jpg", "images/pic2.jpg", "images/pic3.jpg", "images/pic4.jpg", "images/pic5.jpg", "images/pic6.jpg");

function makeCookie() {
var idx = Math.floor((Math.random()* 6));
document.cookie="last=" + idx;
}

function dont() {
var lastinx=document.cooke.indexOf("last=");
if(lastidx != -1) {
var begin = lastidx + 5;
var end = document.cookie.indexOf(";", begin);
if(end == -1) { end=document.cookie.length;}
whichpic = unescape(document.cookie.substring(begin, end));
if(whichpic <6) {
idx = whichpic +1;}
else {
idx = 1;}

function displayimage() {
document.write("<img src='"+images[idx]+"'>");
}
</script>
</head>

<body onLoad="makeCookie(), dont()">
<script type="text/javascript">
displayimage();
</script>
</body>
</html>
 

DHDdirect

New Member
Seems like you have a whole lot of extra code in there that isn't necessary. You shouldn't need cookies for this application.

Try the following (of course the more images you have in the array the more likely the same image wont come up a second time)

Code:
<script language="JavaScript">
<!--
var imglocation = "http://www.webdesignforum.com/images/";
var displayimage = new Array ("pic1.jpg", "pic2.jpg", 
"pic3.jpg", "pic4.jpg", "pic5.jpg");

var idx = Math.floor(6*Math.random());

document.write('<img src="' + imglocation + displayimage[idx] + '" width="100%"
height="100%" alt="images" />');

//-->
</script>

For some reason the forum enters in it's domain when inserting images/ code so ignore that part ;-) in the imglocation variable
 
Last edited:

ehdeelee

New Member
^ Well I mean, the reason he was using cookies was because he wants to know which images the end user hasn't seen yet. Your code doesn't and I don't know any other way of knowing which images they have/haven't seen without using cookies......

I'd be interested in seeing the solution if @Maggarama ever figures it out.
 

DHDdirect

New Member
I need for it to display a random image, but a different one each time the page loads.

This qoute does not specify that they do not want to display images to users that are already displayed in the past. Besides, the more images you have to randomize the less of a chance the user will see the same images twice.
 

Maggarama

New Member
Thanks, DHDdirect. I ended up just using a solution similar to the one you suggested. I was aiming to come up with code that would prevent the same image from displaying twice in a row like ehdeelee said, but the simpler solution was sufficient for my needs.
 
Top