Random Image on page refresh

Hi, I have code like below for the random images in a page refresh. Now i need to give separate href link to each image, How can i do it . If you have a better code for doing this please let me know. Thanks in Advance.

<div class=“one-fourth last”>

  &lt;div class="thumbnail-link"&gt;
   &lt;div id="randomImage"&gt;&lt;a href=""&gt;&lt;/a&gt;&lt;/div&gt;
   &lt;div id="randomImage2"&gt;&lt;a href=""&gt;&lt;/a&gt;&lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;script&gt;
  var randomImage = {
    paths: [
      "01.jpg",
      "02.jpg",
      "03.jpg"
    ],
    
    generate: function(){
      var path = randomImage.paths[Math.floor(Math.random()*randomImage.paths.length)];
      var img = new Image();
      img.src = path;
      $("#randomImage a").html(img);
      $("#randomImage a").attr("href", path);
    }
  }
  
  randomImage.generate();
  
        var randomImage2 = {
    paths: [
      "04.png",
      "05.png",
      "06.png"
    ],
    
    generate: function(){
      var path = randomImage2.paths[Math.floor(Math.random()*randomImage2.paths.length)];
      var img = new Image();
      img.src = path;
      $("#randomImage2 a").html(img);
      $("#randomImage2 a").attr("href", path);
    }
  }
  
  randomImage2.generate();
&lt;/script&gt;

Hi salimali,

I would simply use the below which makes use of objects within your original arrays, also I like to keep logic that doesn’t change much grouped together and simply pass arguments to the given functions which sticks to the D.R.Y rule which means don’t repeat yourself.

Hope that helps.

var randomImage = {
    
    /**
     * The first set of image paths
     */
    paths: [{
        path : '01.jpg',
        url  : 'http://www.google.com/?q=1'
    },
    {
        path : '02.jpg',
        url  : 'http://www.google.com/?q=2'
    },
    {
        path : '03.jpg',
        url  : 'http://www.google.com/?q=3'
    }],

    /**
     * The second set of image paths
     */
    paths2: [{
        path : '04.jpg',
        url  : 'http://www.google.com/?q=4'
    },
    {
        path : '05.jpg',
        url  : 'http://www.google.com/?q=5'
    },
    {
        path : '06.jpg',
        url  : 'http://www.google.com/?q=6'
    }],

    /**
     * Selects a random image and appends it to the target element in the DOM
     * 
     * @param  {Object} images
     * @param  {String} target
     * @return
     */
    generate: function(images, target) {
        var image     = images[Math.floor(Math.random() * images.length)],
            img      = new Image();

        // Append the image and set the `href` attribute
        $(target).find('a').prop('href', image.url).append(img);

        // Load the image now to prevent IE from loading a cached version
        img.src = image.path;
    }

};

// Generate the random images
randomImage.generate(randomImage.paths, '#randomImage');
randomImage.generate(randomImage.paths2, '#randomImage2');

Thanks chris, It works :slight_smile: