0

I have 3 images. 1.jpg, 2.jpg, 3.jpg. I want to distribute them into three img elements randomly (on window refresh, the three images' positions will change).
How do I use Math.random() here? Thanks.

<img src='' id='img1' />
<img src='' id='img2' />
<img src='' id='img3' />
palswim
  • 11,856
  • 6
  • 53
  • 77
yuli chika
  • 9,053
  • 20
  • 75
  • 122

3 Answers3

3

You can shuffle an array you create:

var arr = ["1.jpg", "2.jpg", "3.jpg"];
arr.sort(function() {return 0.5 - Math.random()});

Some people prefer other ways of shuffling, but a shuffling method would work to ensure you get all of the elements only once in your resulting array.

Community
  • 1
  • 1
palswim
  • 11,856
  • 6
  • 53
  • 77
2

There are six different ways that the images can be put in the tags. Pick one of them using random:

var index = Math.floor(Math.random()*6);
var ids = [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]][index];
document.getElementById('img'+ids[0]).src = '1.jpg';
document.getElementById('img'+ids[1]).src = '2.jpg';
document.getElementById('img'+ids[2]).src = '3.jpg';
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1
Math.floor(Math.random()*3)+1;

But distribution won't be uniform.