Tutorials - JavaScript: Image change on page reload
Another nice feature is to have an image change each time the page is reloaded. Visually this is nice, creating a different look each time a visitor sees your Web page.
Step 1
Copy the JavaScript below and paste
it into the <head> section of your HTML
document.
<script language="JavaScript" type="text/javascript">
<!-- Hide from old browsers
iArray=new Array(
"images/index_imageswap.gif",
"images/imageswap2.gif",
"images/imageswap3.gif",
"images/imageswap4.gif",
"images/imageswap5.gif");
ri=Math.floor(iArray.length*Math.random());
ri='<img src="../'+ iArray[ri]+ '" border=0>';
// end hiding -->
</script>
Step 2
Change the references to the images to match your image file names and directory structure. Here is the text from above, now in bold, that you need to change.
"images/index_imageswap.gif",
"images/imageswap2.gif",
"images/imageswap3.gif",
"images/imageswap4.gif",
"images/imageswap5.gif"
Step 3
Copy the JavaScript below and paste it into
the <body> section of your HTML document
where you want to place the image.
<script language="JavaScript" type="text/javascript">
<!--document.write(ri);
// -->
</script>
Example
Reload/refresh this page to see the image change below. The image displayed is randomly picked from a list (an array), therefore, the same image may appear sequentially.
last reviewed: January 25, 2008
