Skip to content Skip to sidebar Skip to footer

Selecting A Random Image To Display

I have a page that contains 4 images. I would like these images to be chosen randomly from a selection of images, each time the page is viewed. The images also need to link to a sp

Solution 1:

It can be done by creating an array of the possible images, shuffling the array, then grab the first 4 images and append to the div:

// randomize array functionArray.prototype.shuffle = function() {
  var i = this.length, j, temp;
  if ( i == 0 ) returnthis;
  while ( --i ) {
     j = Math.floor( Math.random() * ( i + 1 ) );
     temp = this[i];
     this[i] = this[j];
     this[j] = temp;
  }
  returnthis;
}

// declare image data as array of objectsvar images = [
    { src : 'images/image_01.jpg', href : 'page_082.html' },
    { src : 'images/image_02.jpg', href : 'page_083.html' },
    { src : 'images/image_03.jpg', href : 'page_084.html' },
    { src : 'images/image_04.jpg', href : 'page_085.html' },
    { src : 'images/image_05.jpg', href : 'page_086.html' },
    { src : 'images/image_06.jpg', href : 'page_087.html' }
];

$(document).ready(function(){

    var img, anchor, div;
    var cont = $('.socialphoto_container');
    cont.children().remove();

    images.shuffle();

    for(var i=0; i<4; i++){
        img = $('<img />', { src : images[i].src });
        anchor = $('<a></a>', { href : images[i].href, target : '_self' });
        div = $('<div></div>', { class : 'socialphoto' });
        anchor.append(img);
        div.append(anchor);
        cont.append(div);
    }
});

Array.shuffle() is the Fisher-Yates algorithm, taken from here.

Post a Comment for "Selecting A Random Image To Display"