0

I am trying to select a random element from an array and display it using jQuery. So far I can only click through the array and reset back to 0. Not sure how to use the Math.random(); exactly here.

Codepen: http://codepen.io/Travo100/pen/xAKji

counter = 0;

var compArray = [ "Cat", "Dog", "Rabbit", "Cow", "Sheep", "Human" ];

$('a').click(function () {

    counter = (counter + 1) % compArray.length;
    $(this).html(compArray[counter]);

});
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Travo100
  • 61
  • 8

1 Answers1

0

Use this:

var rand = compArray[Math.floor(Math.random() * compArray.length)];
juvian
  • 15,875
  • 2
  • 37
  • 38