Forum Moderators: mack

Message Too Old, No Replies

How to display a random image using Javascript.

I want a different image to appear with each view of a page.

         

jetnovo

5:57 am on May 11, 2004 (gmt 0)

10+ Year Member



Hi there

I'm building a site in HTML, which I am reasonably ok with, but I am very new to javascript.

I have this idea to have an image on the home page (of one of my pieces of work), that changes each time someone refreshes or revisits the page.

Can anyone suggest the necessary javascript to do this?

Thanks!

[edited by: encyclo at 4:36 pm (utc) on May 14, 2008]

Nutter

7:12 pm on May 11, 2004 (gmt 0)

10+ Year Member



Does it have to be in JS? It's fairly easy with PHP or ASP.

- Ryan

MichaelBluejay

8:22 pm on May 11, 2004 (gmt 0)

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



It's better to do this with Perl because if users have JavaScript turned off (or use JavaScript-less browsers like Lynx) then it doesn't work for them. Of course, easier said than done, writing your first Perl CGI script is a lot harder than writing your first JavaScript. I have a good tutorial about that but I don't think I'm allowed to link to it here.

Fortunately, we can use the <noscript></noscript> tags to display a static image, so if the user doesn't have JavaScript, at least they see *some* image, even if it's not a random image.

So here's your image-changing script:


<HTML><HEAD>
<SCRIPT language=JavaScript>
function swapImage() {
theImages = new Array("image1.jpg", "image2.jpg", "image3.jpg");
whichImage = Math.floor(Math.random()*theImages.length);
document.write('<IMG SRC="' +theImages[whichImage]+ '">');

}
</SCRIPT>
</HEAD>
<BODY>

<SCRIPT language=JavaScript>
swapImage();
</SCRIPT>
<NOSCRIPT>image.jpg</NOSCRIPT>

</BODY></HTML>

MichaelBluejay

8:25 pm on May 11, 2004 (gmt 0)

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



Whoops, correction to my code, the <NOSCRIPT> tag should be:

<NOSCRIPT><IMG src="image1.jpg"></NOSCRIPT>

Of course, you need to change the filenames to match your own images anyway....

jetnovo

10:05 pm on May 11, 2004 (gmt 0)

10+ Year Member



Great, thanks guys. I think I'll go with the javascript one because it looks fairly simple. Just one question though - where in the script would I insert height, width, and alt attributes?

MichaelBluejay

10:05 am on May 12, 2004 (gmt 0)

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



Assuming all the images are the same size, then put the attributes between "IMG" and "SRC". If they're not all the same size, can't you just omit them? The browser will figure out how big the pictures are once it loads them.

If the images are different sizes, and you really want to code unique sizes for each one, your script is gonna have to be a bit more complicated....

contentmaster

3:13 pm on May 12, 2004 (gmt 0)

10+ Year Member



Hi

I wanted to do a similar thing on my website ...display diff image each time the page is refreshed......but i want it to do something futher...i want to link the images to their respective html pages....

how can i do this?

please help with the code

Dayo_UK

3:25 pm on May 12, 2004 (gmt 0)



Contentmaster - Something like this should work:-

<script language="JavaScript">

<!--
function random_imglink(){
var images=new Array()

images[1]="aa.gif"
images[2]="bb.gif"
images[3]="cc.gif"

var imagelinks=new Array()

imagelinks[1]="aa.htm"
imagelinks[2]="bb.htm"
imagelinks[3]="cc.htm"

var ry=Math.floor(Math.random()*images.length)

if (ry==0)
ry=1
document.write('<a href='+'"'+imagelinks[ry]+'"'+'><img src="'+images[ry]+'" border=0></a>')
}

random_imglink()
//-->
</script>

MichaelBluejay

8:59 pm on May 12, 2004 (gmt 0)

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



Dayo_UK's code isn't truly random: It has the first image show up 50% of the time, and the 2nd & 3rd images each show up only 25% of the time. To fix this:

1. Number the images[] and imagelinks[] 0, 1, 2, instead of 1, 2, 3.
2. Remove the lines that say" if (ry==0) ry=1"

As you can probably tell from the code, an array is a variable that can hold a bunch of different values. The thing about arrays is that in most modern programming languages they start at zero, not one. So images[0] refers to the FIRST image in your list, and images[1] refers to the SECOND image in the list. Yeah, it's confusing, but if you try to work around it, like Dayo_UK did, then you can run into unexpected problems, like your random image picker not being truly random. Best bet is to just get in the habit of starting at 0.

Dayo_UK

9:13 pm on May 12, 2004 (gmt 0)



Aye - good point. Looking at the code it is a bit of a pointless work around.

It was a bit of a cut and paste job as I used the code on one of my sites a while back.

MichaelBluejay

10:57 pm on May 12, 2004 (gmt 0)

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



I learned this the hard way when a statiscian hired me to do some web work, including rotating some banners on his website. I got the different banners to show up when the page was reloaded so I thought I was successful. Weeks later he checked the code (he knows programming but not webbing, which is why he hired me), and informed me that my code was wrong and that it was showing the first and last banners less frequently than it should. This was kind of embarrassing not only because he was paying me and I supposedly knew what I was doing, but also his advertisers were paying him based on how many times their ads *should* have been displayed, and he'd been shortchanging two of them and didn't even know about it. Since then I've been on the sharp lookout for random-picking code that isn't truly random! Without having had that experience I wouldn't have noticed the problem with the code posted above.

WhosAWhata

11:33 pm on May 12, 2004 (gmt 0)

10+ Year Member



if anyone is interested in PHP
<?
$dir = "dir"; // name of the directory
$pictures = glob("dir/{*.jpg,*.jpeg,*.gif,*.png}",GLOB_BRACE);
$img = $pictures[rand(0,count($pictures)-1)];
echo "<img src=\"".$dir."/".$img."\">";
?>
haven't tested but should work

contentmaster

3:50 pm on May 13, 2004 (gmt 0)

10+ Year Member



Hey Dayo_UK , MichaelBluejay

Thanks so much for the script...it worked just right!
Its looking amazing!

WhosAWhata

3:44 am on May 15, 2004 (gmt 0)

10+ Year Member



sorry to go off on the tangent again, but here is the fixed version of the PHP code i posted before, it had one missing $ and a little extra code


[quote]<?
$dir = "pics"; // name of the directory
$pictures = glob("$dir/{*.jpg,*.jpeg,*.gif,*.png}",GLOB_BRACE);
$img = $pictures[rand(0,count($pictures)-1)];
echo "<img src=\"".$img."\">";
?>[/quote]

jetnovo

8:38 pm on May 16, 2004 (gmt 0)

10+ Year Member



Thank you everyone.. all of this is very intersting!
I've tried some of the sites and found a script that seems to be working very well, I'll post it here when I've finished testing it.

Regards,
Jet

BillyMcCool

4:27 pm on May 14, 2008 (gmt 0)

10+ Year Member



I wouldnt use JavaScript for this unless you plan to degrade the code to PHP. It makes the most sense to use PHP for this utility...

You should actually use the mt_rand() function instead of rand(). mt_rand() has been proven to be more efficient in generating true random numbers...

<?
$dir = "pics"; // The relative path to the image directory
$pictures = glob("$dir/{*.jpg,*.jpeg,*.gif,*.png}",GLOB_BRACE);
$img = $pictures[mt_rand(0,count($pictures)-1)];
echo '<img src="' . $img . '">';
?>