|
|
#1 |
|
New Member
![]() Join Date: Dec 2010
Posts: 5
|
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> |
|
|
|
|
|
#2 |
|
Gold Member
![]() Join Date: Feb 2011
Location: Australia
Posts: 369
|
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>
Last edited by DHDdirect; 02-21-2011 at 08:16 PM. |
|
|
|
|
|
#3 |
|
New Member
![]() Join Date: Mar 2011
Location: Berkeley
Posts: 3
|
^ 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. |
|
|
|
|
|
#4 | |
|
Gold Member
![]() Join Date: Feb 2011
Location: Australia
Posts: 369
|
Quote:
|
|
|
|
|
|
|
#5 |
|
New Member
![]() Join Date: Dec 2010
Posts: 5
|
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.
|
|
|
|
![]() |
| Tags |
| cookies, javascript, random image |
| Thread Tools | |
| Display Modes | |
|
|