Software, your way.
How To Get Good Custom Software
(Download)
(PDF)
burger menu icon
WillMaster

WillMaster > LibraryWeb Page and Site Features

FREE! Coding tips, tricks, and treasures.

Possibilities weekly ezine

Get the weekly email website developers read:

 

Your email address

name@example.com
YES! Send Possibilities every week!

Random Images

This article shows how to display one or more random images on a web page.

Optionally, a cookie can be set so the same image does not display consecutively. Specifying a cookie name in the JavaScript customization area activates the repetition restriction.

Demonstration
(two random images)

The random image is displayed in a div or other HTML container. An HTML container is any HTML tag that can contain content. Examples are div, span, td, and p.

In this article, I'll refer to the random image's HTML container as a div.

When more than one random image is to be displayed on the page, each random image is in its own div.

Page load may be somewhat faster when the div's style specifies the width and height of the image. It depends on the page.

The demonstration has two random images. One is selected from 5 images. The other from 2 images.

If you'll reload the page, you'll see the two demonstration images change.

Implementing Random Image

Implementation is in two parts:

  1. The div to contain the random image. Or, several divs if more than one random image on the page.

  2. The JavaScript.

The divs containing the random images go in the web page source code where images are to be published. The JavaScript goes anywhere below that point.

The Random Image Source Code

Here are the two divs for the demonstration. Copy them, change them as needed for your implementation.

<div id="one" style="width:150px; height:156px;"></div>

<div id="another"></div>

Note that each div has an id value. The id value will be used in the JavaScript.

The div may contain styles for width and height, if desired, or any other definitions. If the width and height of any of the random images are greater than the div dimensions, the excess can be clipped with CSS definition overflow:hidden;

Put the divs to contain the random images in the web page source code where the images are to be published.

Here is the JavaScript. Customization notes follow.

<script type="text/javascript">
/* 
   Random Image
   Version 1.0
   September 13, 2010

   Will Bontrager
   https://www.willmaster.com/
   Copyright 2010 Bontrager Connection, LLC

   Bontrager Connection, LLC grants you 
   a royalty free license to use or modify 
   this software provided this notice appears 
   on all copies. This software is provided 
   "AS IS," without a warranty of any kind.
*/
// Leave next line as is.
var Images = new Array(); // Leave this line as is.


// CUSTOMIZATION 
//
// Two places to customize.
//
// Place 1:
//
// If repetition restriction is desired, specify a cookie 
//   name. Otherwise, leave the CookeieName value blank ("").

var CookieName = "RandomImagePlacement";


//
// Place 2:
//
// For each div (or other HTML container) that will contain 
//   a random image:
//
//   Copy the line below (without the leading "//") --
//
//        Images["A"] = "B";
//
//     and paste it into the JavaScript code below this 
//     comment block.
//
//   Then --
//
//     i. Replace A between the quotation marks with the id 
//        value of the div (or other container).
//
//    ii. Replace B between the quotation marks with a list 
//        of image file SRC= URLs separated with a space. 

Images["one"] = "https://www.willmaster.com/software/productimages/smgateway.jpg https://www.willmaster.com/software/productimages/smsyndicator.jpg https://www.willmaster.com/software/productimages/smformV4.jpg https://www.willmaster.com/software/productimages/smquiz.jpg https://www.willmaster.com/software/productimages/smrecommendpro.jpg";

Images["another"] = "https://www.willmaster.com/software/productimages/ImageShield.gif https://www.willmaster.com/software/images/FormToDatabase_Logo.jpg";


//
// No other customizations required.
////////////////////////////////////
function DisplayRandomImages() {
var Now = Array();
var Prior = Array();
CookieName = CookieName.replace(/\W/g,"");
if(CookieName.length) { Prior = GetCookiePriorInformation(); }
for(var container in Images) {
   var imgstring = Images[container].replace(/^ */,"");
   imgstring = imgstring.replace(/ *$/,"");
   imgstring = imgstring.replace(/  +/g," ");
   var list = imgstring.split(" ");
   var img = 0;
   if(list.length > 1) {
      var img = Math.ceil(Math.random()*list.length)-1;
      while(img == Prior[container]) {
         img = Math.ceil(Math.random()*list.length)-1;
         }
      }
   Now[container] = img;
   var content = '<img src="'+list[img]+'" />';
   document.getElementById(container).innerHTML = content;
   if(CookieName.length) { StoreCookiePriorInformation(Now); }
   }
}

function GetCookiePriorInformation() {
var ck = new String();
var retarray = new Array();
var cookiebegin = document.cookie.indexOf(CookieName + "=");
if(cookiebegin > -1) {
   cookiebegin += 1 + CookieName.length;
   cookieend = document.cookie.indexOf(";",cookiebegin);
   if(cookieend < cookiebegin) { cookieend = document.cookie.length; }
   ck = document.cookie.substring(cookiebegin,cookieend);
   }
if( ck.length ) {
   var parts = ck.split("&");
   for(var i=0; i<parts.length; i++) {
      var tarray = parts[i].split("=");
      retarray[tarray[0]] = tarray[1];
      }
   }
return retarray;
}

function StoreCookiePriorInformation(now) {
var parts = new Array();
for(var indice in now) { parts.push(indice+"="+now[indice]); }
document.cookie = CookieName + "=" + parts.join("&");
}

DisplayRandomImages();
</script>

The JavaScript needs to be somewhere below the divs with the random images. The JavaScript may be imported from an external file (see the Importing JavaScript From An External File article).

The JavaScript has two places to customize.

  1. Cookie name — If repetition restriction is to be enabled, specify a cookie name. Otherwise, make the cookie name blank (two quotation marks with nothing between them).

  2. Image SRC URLs — Here, specify the SRC URLs of the images from which to make a random selection. The URLs may be absolute or relative. List the image SRC URLs with a space between them.

    An absolute URL is the full http://... URL or the image file. A relative URL is the local location of the image file. Here is an example of each, respectively:

    http://example.com/images/image.png
    /images/image.png
    
    

    Each div to contain a random image has a separate list of image SRC URLs that pertain to that div.

    The JavaScript source code contains an example of how to specify the image SRC URLs.

Implementing Random Images consists of placing a div (or other HTML container) into the source code at the place where the random image is to be published. If more than one random image is to be published, place more than one div.

The JavaScript goes anywhere JavaScript can run below the random image divs. The JavaScript source code contains instructions and examples for customizing it.

The source code of divs and JavaScript provided in this article can be pasted into a test web page, without customization, to see the demonstration work on your website.

Will Bontrager

Was this article helpful to you?
(anonymous form)

Support This Website

Some of our support is from people like you who see the value of all that's offered for FREE at this website.

"Yes, let me contribute."

Amount (USD):

Tap to Choose
Contribution
Method

All information in WillMaster Library articles is presented AS-IS.

We only suggest and recommend what we believe is of value. As remuneration for the time and research involved to provide quality links, we generally use affiliate links when we can. Whenever we link to something not our own, you should assume they are affiliate links or that we benefit in some way.

How Can We Help You? balloons
How Can We Help You?
bullet Custom Programming
bullet Ready-Made Software
bullet Technical Support
bullet Possibilities Newsletter
bullet Website "How-To" Info
bullet Useful Information List

© 1998-2001 William and Mari Bontrager
© 2001-2011 Bontrager Connection, LLC
© 2011-2024 Will Bontrager Software LLC