3

Basically. I am creating a preloader page for my site. I want the icon in the middle of the page to change everytime the visitor comes to my page. I need to select a variable or a string within the array.

My code:

$(document).ready(function() {
  //randomly pick a number an pick an icon to show on main page

  //Math.floor(Math.random() * 6) + 1 [from SOF]

  var min = 1,
    max = 8;

  var number = Math.floor(Math.random() * (max - min + 1) + min);

  var icons = ['preload/img/audio.svg', 'preload/img/bars.svg', 'preload/img/grid.svg', 'preload/img/oval.svg', 'preload/img/puff.svg', 'preload/img/rings.svg', 'preload/img/tail-spin.svg', 'preload/img/three-dots.svg'];

  alert(number);
});

I have tried alert(icons.get(numbers)); but never worked. I have been searching for a while and cannot figure it out.

Josh Murray
  • 619
  • 5
  • 18
  • Ehh `icons[number]` ? to select source, but still will need to set it on the icon, so post html as well – The Process Mar 25 '16 at 15:39
  • 3
    Possible duplicate of [Get random item from JavaScript array](http://stackoverflow.com/questions/5915096/get-random-item-from-javascript-array) – Vanojx1 Mar 25 '16 at 15:43

2 Answers2

1

You need to retrieve the icon using the index.

Also, for the random, it returns a float between 0 and 1, so as an array is 0 based, and you have 8 items, you need to:-

$(document).ready(function() {

  var number = Math.round(Math.random() * 7);

  var icons = ['preload/img/audio.svg', 'preload/img/bars.svg', 'preload/img/grid.svg', 'preload/img/oval.svg', 'preload/img/puff.svg', 'preload/img/rings.svg', 'preload/img/tail-spin.svg', 'preload/img/three-dots.svg'];

  alert(icons[number]);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
BenG
  • 14,826
  • 5
  • 45
  • 60
  • Ahh yes. I have coded in VB.NET and used the index for arrays but I thought JavaScript and jQuery worked differently. Thank you for the help. – Josh Murray Mar 25 '16 at 21:08
0
var icons = ['preload/img/audio.svg', 'preload/img/bars.svg', 'preload/img/grid.svg', 'preload/img/oval.svg', 'preload/img/puff.svg', 'preload/img/rings.svg', 'preload/img/tail-spin.svg', 'preload/img/three-dots.svg'];
var imageNum = Math.floor(Math.random()*icons.length);
document.getElementById("myIcon").src = icons[imageNum];

Where "myIcon" is the id of the image you want to change.

jimboweb
  • 4,362
  • 3
  • 22
  • 45