0

enter image description here

My requirement: I have 3 set of images- Large images, Vertical images, Rectangle images. When page is refreshed, In the shown layout, I want to display random image of the same set.

My problem is, only first large,vertical,rect angle div is displaying image randomly on every refresh. The other all images are showing the same as previous.

HTML Code:

<div class="largebox">            
  <a href="">             
    <img id="largeimg" src="" class="largeimage">
  </a>          
</div>

Jquery Code:

  <script language="javascript">
      // random number between 1 and 100
      var numRand = Math.floor(Math.random()*13);
      document.getElementById("largeimg").src = "img/IMG_"+numRand+".jpg";
    </script>
Vamsi Abbineni
  • 479
  • 3
  • 7
  • 23

2 Answers2

0

EDIT

assuming you want unique images to be displayed, calling

var numRand = Math.floor(Math.random()*13);

inside the loop may yield repeat values, hence the suggestion of creating a random value array first

----

I instantly thought of how this might work, you'd need an array with random values (1-100), and an array with the image elements, and you'd loop though the arrays and assign the random array value to the image element

so on page load create an array [1, 2, 3, 4, 5... 100] (with a loop) and the array of image elements

then shuffle the values with shuffle javascript array values

take a = array with random numbers

take b = array with image elements (document.getElementsByClassName("largeimage"))

for (var i = 0; i < a.length; i++) {

b[i].src = "img/IMG_"+a[i]+".jpg";

}

i hope it helps, i did not model and test this

Community
  • 1
  • 1
0

Lets consider your HTML to be

<div class="largebox">            
  <a href="">             
    <img id="largeimg1" src="" class="largeimage">
  </a>          
</div>

<div class="largebox">            
  <a href="">             
    <img id="largeimg2" src="" class="largeimage">
  </a>          
</div>

Then your JS code should look like

var count = $('.largebox').length;

for(var i = 1; i <= count; i++)
{
    var numRand = Math.floor(Math.random()*13);
    var src1 = "img/IMG_"+numRand+".jpg";
    $('#largeimg'+i).attr("src", src1);
}

This is considering classes largebox, largeimage and ids largeimg1, largeimg2 are to be used only for Large images.

You can follow similar procedure for Vertical images and Rectangle images.

Hope that helps you!

Suyog
  • 2,472
  • 1
  • 14
  • 27