Skip to content Skip to sidebar Skip to footer

Randomizing The Order Of Divs On Page Load With Jquery?

I'm working on my first website (personal use for my portfolio). I have content in divs, but want them to reorder in randomly each time the page is reloaded. I tried to search for

Solution 1:

The following will get them out of the dom and print them back out randomly.

$(document).ready(function() {
//get list of divsvar div = $(".box").toArray();

//randomly print them back out.while(div.length > 0) {
    var idx = Math.floor((Math.random() * (div.length-1)));
    var element = div.splice(idx, 1);
    $('body').append(element[0]);
}
});

Solution 2:

Try this:

var divs = [];
var divs_shuffle = shuffle($('.box').get());
for(var i in divs_shuffle){
  divs.push(divs_shuffle[i].outerHTML);
}
$('body').html(divs.join(''));

You can find shuffle() function here https://stackoverflow.com/a/6274398/2604607

Solution 3:

Sorry for the late, response, I hope this still helps you. Here you have a live fiddle: http://jsfiddle.net/J5z4n/1/ and below you have the source code. You may replace 10 with another number bigger than your number of elements. The idea is to save the innerHTMLs of the target tags and then swap them.

var elements = $("div");
var elementsInnerHtmls = [];
var numberOfElements = elements.length;

for( var i = 0 ; i < numberOfElements ; i++){
    elementsInnerHtmls.push(elements[i].innerHTML); 
}

var checkedIndexes = [];
for( var i = 0 ; i < numberOfElements ; i++){
    var randomIndex = Math.floor(Math.random()*10) % numberOfElements;
    while(checkedIndexes[randomIndex] != undefined){
        randomIndex = Math.floor(Math.random()*10) % numberOfElements;    
    }
    checkedIndexes[randomIndex] = true;
    elements[i].innerHTML = elementsInnerHtmls[randomIndex];    
}

Post a Comment for "Randomizing The Order Of Divs On Page Load With Jquery?"