Skip to content

Instantly share code, notes, and snippets.

@jwdeane
Created January 21, 2010 10:32
Show Gist options
  • Save jwdeane/282714 to your computer and use it in GitHub Desktop.
Save jwdeane/282714 to your computer and use it in GitHub Desktop.
display random image with jQuery
// Basic Random Image Rotator
// jQuery required http://jquery.com
// Easy option
// img is an array of images
var img = ['img1.jpg','img2.jpg','img3.jpg','img4.jpg'];
// src="images/rotator/ is path to your files contained in above array
$('<img src="images/rotator/' + images[Math.floor(Math.random() * images.length)] + '">').appendTo('#imageContainer');
////////////////////////////
// ALTERNATIVELY use JSON //
////////////////////////////
// Below, replace 'js/images.json' with the path to your JSON file
$.getJSON('js/images.json', function(data) {
var item = data.images[Math.floor(Math.random()*data.images.length)];
$('<img src="images/rotator/' + item.image + '">').appendTo('#imageRotator');
$('<p>' + item.caption + '</p>').appendTo('#imageRotator');
});
// sample JSON - put all of this in it's own file
// name it 'whatever.json'
{
"images":[
{
"image":"img1.jpg",
"caption":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam porta, lorem ac fermentum condimentum, velit magna ullamcorper eros, semper volutpat velit ligula ut turpis."
},
{
"image":"img2.jpg",
"caption":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam porta, lorem ac fermentum condimentum, velit magna ullamcorper eros, semper volutpat velit ligula ut turpis."
},
{
"image":"img3.jpg",
"caption":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam porta, lorem ac fermentum condimentum, velit magna ullamcorper eros, semper volutpat velit ligula ut turpis."
},
{
"image":"img4.jpg",
"caption":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam porta, lorem ac fermentum condimentum, velit magna ullamcorper eros, semper volutpat velit ligula ut turpis."
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment