Randomizing the position of images

1

I have a list with 10 images and I need to make every time there is a refresh on the page these images change position.

    
asked by anonymous 06.02.2014 / 20:30

4 answers

5

Assuming that when you say "I have a list with 10 images" you mean something like:

<ul id="minhaLista">
    <li><img src=... /></li>
    <li><img src=... /></li>
    ...
</ul>

If you want these images in a random order, I suggest using the Fisher-Yates algorithm >:

var ul = $("#minhaLista");
var lis = $.makeArray(ul.children().detach()); // Remove todos os lis e converte num array
for ( var i = 0 ; i < lis.length ; i++ ) {
    var proxima = Math.floor(Math.random()*(lis.length - i) + i); // Sorteia um
    ul.append(lis[proxima]); // Coloca de volta na lista
    lis[proxima] = lis[i];  // Retira ele dos "ainda não sorteados"
}

Example in jsFiddle .

If your goal on the other hand is for a random image to be the "first", but the others remain in the same order (as if you had "passed" a random number of times), pass all the previous pro end of the list:

var ul = $("#minhaLista");
var lis = ul.children();
var sorteada = Math.floor(Math.random()*lis.length);
for ( var i = 0 ; i < sorteada ; i++ )
    lis.eq(i).detach().appendTo(ul);

Example in jsFiddle .

    
06.02.2014 / 23:43
2

One way to do this, using javascript pure and without jQuery is listed below

/**
 * Shuffle Fisher-Yates algorithm
 * 
 * @see http://sroucheray.org/blog/2009/11/array-sort-should-not-be-used-to-shuffle-an-array/
 * @param   {Array}   array
 * @returns {Array}
 */
function shuffle (array) {
    var i = array.length, j, temp;
    if (i === 0) {
        return array;
    }
    while (--i) {
        j = Math.floor(Math.random() * (i + 1));
        temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}

/**
 * Para um elemento pai e um array contendo nomes de arquivos, adiciona randomicamente filhos a este pai.
 * 
 * @param   {DOMElement}   el      Elemento pai. Ex: document.getElementById('id-do-elemento'), jQuery('#id-do-elemento')
 * @param   {Array}        array   Array contendo a parte que muda do local da imagem
 * @param   {String}       [base]  Base do caminho
 * @returns {DOMElement}
 */
function randonImgAppendChild (el, array, base) {
    var i, base = base || '', img;
    array = shuffle(array);

    for (i = 0; i < array.length; i += 1) {
        img = new Image(); // Imagem. Poderia ser qualquer outro elemento
        img.src  = base + array[i];
        el.appendChild(img);
    }
    return el;
}

In this case, the shuffle function is used to randomize an array ( Array.sort and Math.randon are not very efficient depending on how they are used), and the randonImgAppendChild function actually does the service. The code is commented so just read on it.

Example usage:

randonImgAppendChild(document.body, ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg', '7.jpg', '8.jpg', '9.jpg', '10.jpg'], '/pasta/base/');
randonImgAppendChild(document.getElementById('mainbar'), ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg', '7.jpg', '8.jpg', '9.jpg', '10.jpg'], '/pasta/base/');

Note: the previous response was based on the extramaster's OS , but it is not very good.

    
06.02.2014 / 22:46
1

1 - Rename images from 1 to 10, for example:

1.jpg, 2.jpg e assim por diante.

2 - Add an id to the element where the images were, for example:

id="bannerRandom"

var totalCount = 10;
function ChangeIt(){
  var num = Math.ceil( Math.random() * totalCount );
  document.getElementById("bannerRandom").style.backgroundImage = "url('/images/"+num+".jpg')";
} 

In the url, pass the location where the images are located.

Remembering that in this way the images are not going to follow an order and are presented randomly.

    
06.02.2014 / 20:38
1

If you're using PHP , this will help you:

$randomImg = ['img1.jpg', 'img2.jpg', 'img3.jpg', 'img4.jpg', 'img5.jpg', 'img6.jpg', 'img7.jpg', 'img8.jpg', 'img9.jpg', 'img10.jpg'];
shuffle($randomImg);
echo $randomImg[0];

I'd rather do it myself than in css / javascript

    
07.02.2014 / 12:01