Random Image Function

Mindwatering Incorporated

Author: Tripp W Black

Created: 04/22/2013 at 10:33 AM


Notes Developer Tips

Have image randomly change each refresh/load of the page.

$.randomImage = {
defaults: {
// update the list below with the path's and then the image names
path: '/Folder/app.nsf/',
myImages: ['image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg', 'image5.jpg' ]
randomImage:function(config) {
var config = $.extend({}, $.randomImage.defaults, config);
return this.each(function() {
var imageNames = config.myImages;

//get size of array, randomize a number from this number as the array index
var imageNamesSize = imageNames.length;
var lotteryNumber = Math.floor(Math.random()*imageNamesSize);
var winnerImage = imageNames[lotteryNumber];
var fullPath = config.path + winnerImage;

//put this image into DOM at class of randomImage
// alt tag will be image filename.
$(this).attr( {
src: fullPath,
// alt: winnerImage // uncomment if alt tag desired

<script type="text/javascript">$(window).load(function(){
var initialBg = $('body').css("background-image");
var arr = [initialBg, "url(/Folder/MyApp.nsf/webIF/bg-index-2.jpg/$FILE/bg-index-2.jpg)", "url(/Folder/MyApp.nsf/webIF/bg-index-3.jpg/$FILE/bg-index-3.jpg)", "url(/Folder/MyApp.nsf/webIF/bg-index-4.jpg/$FILE/bg-index-4.jpg)", "url(/Folder/MyApp.nsf/webIF/bg-index-5.jpg/$FILE/bg-index-5.jpg)", "url(/Folder/MyApp.nsf/webIF/bg-index-6.jpg/$FILE/bg-index-6.jpg)", "url(/Folder/MyApp.nsf/webIF/bg-index.jpg/$FILE/bg-index.jpg)"];
var imageArrSize = arr.length;
var randomSelect = Math.floor(Math.random()*imageArrSize);
var imageWinner = arr[randomSelect];
var bgImage = imageWinner;$('body').css('background-image', bgImage);

previous page