Randomize the position of the images

Asked

Viewed 2,213 times

1

I have a list of 10 images and I need to make sure that every time there’s one refresh on the page these images change position.

  • 7

    Breno, welcome! If you put here the HTML code of the images you have, you will get a correct answer.

  • 4

    You can explain better what you want to do, especially the "change position"?

4 answers

5


Assuming that when you say, "I have a list of 10 images," you refer to 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 that a random image is the "first", but the others remain in the same order (as if you had "passed forward" a random number of times), just draw an image and pass all the previous ones to the 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.

  • 1

    Your answer is better than mine. You can note that it requires jQuery?

  • 1

    @Emersonrochaluiz I found it unnecessary, since the jquery tag is in the question (in general, questions with the javascript tag only "ask" a pure Javascript answer, while asking with the jquery tag already implies that the answers may involve jQuery). Anyway, I gave +1 in your comment, this should be enough to draw attention to the fact.

  • Well remembered. The question is not even marked with javascript, but only jquery. You’re right.

2

One way to do this, using pure javascript 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 function shuffle is used to randomize an array (Array.sort and Math.randon are not very efficient depending on how they are used), and the function randonImgAppendChild is that effectively does the job. The code is commented so just read on it.

Example of use:

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 answer was based on the extramaster OS response, but she’s not very good.

  • For those who want a jQuery solution instead of pure javascript, the @mgibsonbr response is better

  • One thing I didn’t understand either in your answer or in the original extramaster is the value of for: why 23 (or 18)? In the linked question, the OP wanted 16 images from a set of 10 (that makes more sense, but in my reading it should still be 16). Is there a reason for this number?

  • 1

    @mgibsonbr I edited the answer. Now it’s definitely understandable. Easier to do right than explain the guy’s POG.

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')";
} 

url, pass the location where the images are located.

Remembering that this way the images will not follow an order but will be presented randomly.

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 css/javascript

Browser other questions tagged

You are not signed in. Login or sign up in order to post.