Adding random static images to your web-site

There are times when one wishes to add just a “simple” static photo to improve feel and presentation of our/client’s site or photo blog. The idea usually goes like this:

  • I have a series of images that I want to display on my website.
  • I do not need a slideshow.
  • I just want to display one image (on the page load) and I want to grab it at random.
  • My site is either based on WordPress theme or it is just a plain xhtml site.

To accomplish this task, three web components are needed: html, css, and some sort of JavaScript. For the latter, I picked jQuery library which is well suited for this task. In addition, other standard web technologies will be used, such as JSON and Ajax.

Prerequisites:

For the following part, we will need to be comfortable with a simple editing of html code, preparing JSON list of our photos, including jQuery/Ajax script, and with a little bit of css styling.

Putting all things together:

First, we start off with creating a structured list that will contain file name and title (description) of our photos. In this example, we have five photos with two data sets for each (title and url). Feel free to add, replace, or remove photos from this file, but always make sure that its structure remains the same. “Title” is essentially a header or photo description that will be displayed with it and “url” field takes the file name of your image.
I often check integrity of JSON file at: Jsonlint.

Example of JSON file – images.json

// Building jason list
{"images":[ 	 
{ 	 
	"title": "Sunset at the Horshoe Bend, AZ", 	 
	"url": "1.jpg"	  
	 },	 
	 {	 
	"title": "Kauai Highlands", 	 
	"url": "2.jpg" 
	 },	 
	 {	 
	"title": "Storm is coming", 	 
	"url": "3.jpg"
	 },	 
	 {	 
	"title": "Venice - Grand Canal view from the Rialto Bridge", 	 
	"url": "4.jpg" 
	 },	 
	 {	 
	"title": "Mexican wolf", 	 
	"url": "5.jpg"  
	 }	 
	 ] 	 
}

Next, save the above code as images.json and create a new directory on your web server where all images and the just saved .json file will be located. I have chosen images_rand to distinguish it from common web-site images. For example, if your web site is at www.yoursite.com, new directory would go to: www.yoursite.com/images_rand. Again, this is where both images and the above images.json file would go.

Editing html page:

This is a very simple step: just place new div element into your html document, somewhere between the body tags:

<body>
......
<div id="singleshot"> 	 
</div>
......
</body>

I have assigned this element new id and called it “singleshot”. This is where the random image and description will be injected by the jQuery call.

Styling the image:

Position and style can be adjusted in css stylesheet which gets loaded with your page. You can find its name by viewing the page source from any browser.
The link that you are looking for is in the head sections. For example:

Part of the html head section

<head>
.....
<link rel="stylesheet" href="http:/www.yoursite/css/style.css" type="text/css" media="all" />
.....
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js?ver=1.6.2'></script>
.....
</head>

Example of css file

#singleshot {
 		padding:7px; 
 		background-color: rgb(80,80,80); 
 		-moz-border-radius: 5px; 
 		-webkit-border-radius: 5px; 
 	      border-radius: 5px;
       	margin-bottom: 60px;
       	width:665px;
       	height: 499px;
            }
#singleshot p {
	       background: rgba(90,90,90,0.3);
	       color: rgb(20,20,20);
	       position: relative;
	       top: -500px;
	       margin: 0 0 0 0 ;
	       padding: 5px 0 5px 0;
	       text-align: center;
	       font-family: Arial, Helvetica;
	       font-size: 2.2em;
	       font-weight: bold;
             }        

I have assigned this element new id called “singleshot”. This is where the image and description will be injected by jQuery call.

jQuery code:

First, we need to include jQuery library into our page. To accomplish this, include its source into the head section as shown above (part of the html section, line 5). The latest (Aug 2012) source is always at: Google Ajax API CDN.
Check for the most recent version at: jQuery main web site .
Enter the following script into the html body, just before the “singleshot” div element at line 3 above (Editing html page).

<script type="text/javascript">
  jQuery.getJSON('http://www.yoursite.com/../images_rand/images.json', function(data) { //Ajax call
         var item = data.images[Math.floor(Math.random()*data.images.length)]; //select image at random
         //build the complete <img> tag
         jQuery('<img src="http://yoursite.com/../images_rand/' + item.url + ' " width="665px" height="499px">').appendTo('#singleshot');
         jQuery('<p>' + item.title + '</p>').appendTo('#singleshot'); //attach "title" to separate <p> tag
});
</script>
Since I was adapting this script for a WordPress template, I use jQuery instead of $ sign in the front of jQuery statements (else the script won’t work in WordPress).

The script starts with Ajax call to images.json file located on your server. Data is read into an array and random entry is assigned to a variable item. In the next step, the complete img tag is built by adding the image file name (url) and image dimensions, which are constant for the web page. Once done, the img tag is appended to #singleshot id in the empty div element. The last step of our script grabs the title and places it into a separate p tag.
That’s all. Change the path to your images.json file and image dimensions to fit your page.

Final result is at the lower part of my Photography web site.

Example of working script at photo.marcelpatek.com

While the code above works just fine, color of the description text sometimes does not match the image lightness. If we were just able to change the text color depending on image tones … Read below.

Further improving our script:

In order to match the image density with color of the description header, we have to modify two parts. Namely, the json file and the jQuery/Ajax script.
Below is the new json list with additional tag, called “scene”. This is where we define the image category (light, dark, normal). Each category will then be used to change the css style of our description text.

// Modified jason list (images1.json)
{"images":[ 	 
{ 	 
	"title": "Sunset at the Horshoe Bend, AZ", 	 
	"url": "1.jpg",
	"scene": "light"	  
	 },	 
	 {	 
	"title": "Kauai Highlands", 	 
	"url": "2.jpg",
	"scene": "dark" 
	 },	 
	 {	 
	"title": "Gathering before the storm", 	 
	"url": "3.jpg",
	"scene": "light"
	 },	 
	 {	 
	"title": "Venice - Grand Canal view from the Rialto Bridge", 	 
	"url": "4.jpg",
	"scene": "normal" 
	 },	 
	 {	 
	"title": "Mexican wolf in Sonora Desert Museum in Tucson, AZ", 	 
	"url": "5.jpg",
	"scene": "normal"  
	 }	 
	 ] 	 
} 	

Save the list as images1.json and upload it into the same directory as the images.json file above.

Now, the jQuery part. We define several additional variables to describe the color and the text background. Then, depending on the image category, empty variable scene is assigned the corresponding values and it is passed as a style into the p element at line 15.

<script type="text/javascript">
  jQuery.getJSON('http://www.yoursite.com/../images_rand/images1.json', function(data) {
       var item = data.images[Math.floor(Math.random()*data.images.length)];
       //change rgb values below for the best color-match
       var light = "color: rgb(20,20,100); background: rgba(190,190,190,0.25)";
       var dark =  "color: rgb(255,206,0); background: rgba(90,90,90,0.25)";
       var normal = "color: rgb(230,184,0); background: rgba(90,90,90,0.25)";
       var scene = ""; //keep the original style
       
		if (item.scene == 'dark') {scene = dark}
		else if (item.scene == "light") {scene = light} 
	      else {scene = normal}

       jQuery('<img src="http://www.yoursite.com/../images_rand/' + item.url + ' " width="665px" height="499px" title="Random image" alt="" />').appendTo('#singleshot');
       jQuery('<p style="' + scene + '">' + item.title + '</p>').appendTo('#singleshot');
});
</script>

That’s it. Change the jQuery script on your html page and tweak the color settings between lines 5-7.

Book References

  • Google Book Preview

    jQuery Cookbook
    Cody Lindley

    ISBN: 0596159773
    Publisher: Oreilly & Associates Incorporated
    Published: 2009-11-16

  • JQuery: Novice to Ninja
    Earle Castledine, Craig Sharkie

    ISBN: 0980576857
    Publisher: Sitepoint Pty Limited
    Published: 2010-03-07

No Responses — Written on August 4, 2012 — Filed in: Code, Software, ,

Leave a Reply

Your address will not be published.