0

I've created a script to populate an array with numbers from 0-118 and used a function to shuffle it.

e.g.:

var Arr = new Array ();

for (var i = 0; i < 119; i++) {
    Arr[i] = i;
}

function shuffle(o){ 
    for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};

newArray = shuffle(Arr);

I have a gallery with 24 thumbs that are named 0.jpg, 1.jpg etc 118.jpg. I need to call for each of the thumbs a number from an array.

Equivalent in php would be :

<?php $arr = array_rand(range(1, 117), 24);?>
<img src="images/<?php echo $arr[0].'.jpg'; ?>" />

Can this be done in Javascript? How should i approach it? Creating an array with the thumb's name is not practical.

Cosmin
  • 49
  • 1
  • 3

2 Answers2

0

I managed to do it like this (help from a colleague):

var array           = [];   // create array for the images

for (var i = 0; i < 90; i++) {
    array[i] = i;
}

var new_array       = shuffle(array);   // shuffled array

for (var i = 1; i <= 24 ; i++) {
    $('#' + i).attr('src', 'images/banner/' + new_array[i-1] + '.jpg');
}

window.setInterval(function(){
    var random_position = Math.floor(Math.random() * 24) + 1;   // grab a random position from the grid
    var random_image    = Math.floor(Math.random() * array.length) + 0; // grab a random image

    while ($.inArray(random_image, new_array.slice(0, 24)) > -1) {  // condition to avoid duplicate images
        random_image    = Math.floor(Math.random() * array.length) + 0;
    }

    $('#' + random_position).fadeOut(300, function() {  // change image
        $('#' + random_position).attr('src', 'images/banner/' + random_image + '.jpg');
        $('#' + random_position).fadeIn(300);
    });

    new_array[random_position - 1] = random_image;  // register the change

    return false;

}, 5000);

function shuffle(o){ //  shuffle function
for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;};
Cosmin
  • 49
  • 1
  • 3
0

You could give the images a class and do

$(".imageClass").each(function(i) {
 this.src="/images/"+newArray[i]+".jpg";
});
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • Would this script shuffles the array before adding attr to the class? doing so, might be duplicates? – Cosmin Sep 28 '14 at 20:07
  • I do not quite get your comment. Also I did not look at the shuffle. Here is an alternative:http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array – mplungjan Sep 29 '14 at 04:09