Forum Moderators: open

Message Too Old, No Replies

Load Random IMG

without repeating 2 in a row

         

Two Bass Hit

12:24 am on Jul 13, 2006 (gmt 0)

10+ Year Member



I wrote a simple javascript to randomly load an image from an array when a webpage loads. I would like to modify the script so that the new image that loads would not be the same image that previously loaded. Here is what I have so far (any help would be greatly appreciated)...

-----------------------

myPics = new Array("image1.jpg", "image2.jpg", "image3.jpg")

imgCt = myPics.length

randomNum = Math.floor((Math.random() * imgCt))

function randomPic() {
document.myImage.src = myPics[randomNum]
}

------------------------

Thanks!

penders

10:30 am on Jul 13, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I would have thought you need to use a cookie to 'remember' what image was displayed last. If the new image you pick matches the cookie then pick another one, otherwise replace the cookie with the new image.

birdbrain

10:41 am on Jul 13, 2006 (gmt 0)



Hi there Two_Bass_Hit,

as penders has pointed out, this requires a cookie. ;)


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<script type="text/javascript">
<!--

var num;
var myPics=new Array('image1.jpg','image2.jpg','image3.jpg');
var imgCt=myPics.length;

function testNumber() {
randomNum=Math.floor(Math.random()*imgCt);
if(randomNum==num) {
testNumber();
}
else {
num=randomNum;
document.getElementById('myImage').src=myPics[randomNum];
setCookie();
}
}

function setCookie() {
exp=new Date();
plusMonth=exp.getTime()+(31*24*60*60*1000);
exp.setTime(plusMonth);
document.cookie='Number='+num+';expires='+exp.toGMTString();
}

function readCookie() {
if(document.cookie) {
num=document.cookie.split('Number=')[1];
testNumber();
}
else {
testNumber();
}
}
window.onload=readCookie;
//-->
</script>

</head>
<body>

<div>
<img id="myImage" src="" alt=""/>
</div>

</body>
</html>

birdbrain

Two Bass Hit

8:39 pm on Jul 13, 2006 (gmt 0)

10+ Year Member



birdbrain...
THANK YOU!

birdbrain

10:03 pm on Jul 13, 2006 (gmt 0)



No problem, you're welcome. ;)