Forum Moderators: mack
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]
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>
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....
<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>
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.
It was a bit of a cut and paste job as I used the code on one of my sites a while back.
[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]
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 . '">';
?>