Randomize Children Elements On Load
I want to randomize the children elements of any
,
- on load with javascript. I am searching for the best approach to do it. Can some one help? Suppose i have a
Solution 1:
Quicky out of my head:
- Remove all the items in the
<ul>
withdetach
- Store them in an array.
- Shuffle that array
- Insert elements in
<ul>
again.
Also take a look at this question: randomize div elements
Solution 2:
Here's how I did it (JSFiddle example here: http://jsfiddle.net/LNvqr/2/)
If you use jQuery and have HTML similar to this:
<div><ulid="rndList"><liid="itemOne">one</li><liid="itemTwo">two</li><liid="itemThree">three</li><liid="itemFour">four</li><liid="itemFive">five</li></ul></div>
Then you could simply use .detach to remove and store the array of the <li>
elements.
Next, with a copy of the array, use Math.random()
to generate a (pseudo)random integer between 0 and one less than the size of the array. Use this as the random index to be copied from the original (ordered) list in to the new (randomly-ordered) one.
Remove the randomly-chosen element from the original array on each iteration and choose a new random one until all elements have been re-inserted:
functionshuffleList() {
var origList = $("#rndList li").detach();
var newList = origList.clone();
for (var i = 0; i < newList.length; i++) {
//select a random index; the number range will decrease by 1 on each iterationvar randomIndex = randomInt(newList.length - i);
//place the randomly-chosen element into our copy and remove from the original:
newList[i] = origList.splice(randomIndex, 1);
//place the element back into into the HTML
$("#rndList").append(newList[i]);
}
}
functionrandomInt(maxNum) { //returns a random integer from 0 to maxNum-1returnMath.floor(Math.random() * maxNum);
}
Solution 3:
You can achieve this with below code:
$(function () {
var parent = $("#parent-container");
var divs = parent.children();
while (divs.length) {
parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]);
}
});
Post a Comment for "Randomize Children Elements On Load"