JavaScript - Shuffle HTML List Element Order

javascript - shuffle HTML list element order

var ul = document.querySelector('ul');
for (var i = ul.children.length; i >= 0; i--) {
ul.appendChild(ul.children[Math.random() * i | 0]);
}

This is based on Fisher–Yates shuffle, and exploits the fact that when you append a node, it's moved from its old place.

Performance is within 10% of shuffling a detached copy even on huge lists (100 000 elements).

http://jsfiddle.net/qEM8B/

How can I shuffle a list weekly and have it consistent across all devices?

So shuffling randomly will be inconsistent since it's differs each time you reload the page. To shuffle consistently you can try to create a pseudo random shuffle logic - so avoid using Math.random() here.

Explanation

We need to create a seed, in this case we are calulating the calendar week index and concatting this particular number with the current year to avoid repeating the same shuffle behaviour every year.

const seed = Math.ceil((new Date().getDay() + 1 + Math.floor((new Date() - new Date(new Date().getFullYear(), 0, 1)) / (24 * 60 * 60 * 1000))) / 7) + new Date().getFullYear();

or smaller:

const seed = Math.ceil(((new Date() - new Date(new Date().getFullYear(), 0, 1)) / 86400000 + new Date(new Date().getFullYear(), 0, 1).getDay() + 1) / 7);

We need a "Random"-generator like this simple method:

const getRandom = () => {
const val = seed / (2 ** 32);
seed = (1664525 * seed + 1013904223) % (2 ** 32);
return val;
}

Now we can start shuffeling the entries of our list using the linked answer to this question:

for (var i = list.children.length; i >= 0; i--)
list.appendChild(list.children[getRandom() * i | 0]);

Snippet

Take a look at this working snippet, note that the order of the list will change every week:

// create seed that changes every new week and will not repeat since we concat it with the current year
let seed = Math.ceil(((new Date() - new Date(new Date().getFullYear(), 0, 1)) / 86400000 + new Date(new Date().getFullYear(), 0, 1).getDay() + 1) / 7);

// create pseudo random numbers
const getRandom = () => {
const val = seed / (2 ** 32);
seed = (1664525 * seed + 1013904223) % (2 ** 32);
return val;
}

// pseudo shuffel list
const list = document.querySelector('ol');
for (let i = list.children.length; i >= 0; i--)
list.appendChild(list.children[getRandom() * i | 0]);
<ol>
<li>Al Pacino</li>
<li>Bill Gates</li>
<li>Carsten Stahl</li>
<li>David Beckham</li>
<li>Elon Musk</li>
<li>Frank Ocean</li>
</ol>

How to shuffle list items randomly in JavaScript

here I found easy logic https://stackoverflow.com/a/11972692/6631280

var ul = document.querySelector('#my_div');for (var i = ul.children.length; i >= 0; i--) {    ul.appendChild(ul.children[Math.random() * i | 0]);}
<div class="content-container">        <p>The bluebird <span class="blank"></span> the <span class="blank"></span> on his <span class="blank"></span></p>     </div>
<div class="btn-container"> <ul id="my_div"> <li><a href="#">carries</a></li> <li><a href="#">sky</a></li> <li><a href="#">back</a></li> </ul> </div>

How to randomize (shuffle) a JavaScript array?

The de-facto unbiased shuffle algorithm is the Fisher-Yates (aka Knuth) Shuffle.

You can see a great visualization here (and the original post linked to this)

function shuffle(array) {
let currentIndex = array.length, randomIndex;

// While there remain elements to shuffle.
while (currentIndex != 0) {

// Pick a remaining element.
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;

// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}

return array;
}

// Used like so
var arr = [2, 11, 37, 42];
shuffle(arr);
console.log(arr);

Shuffle a container's DOM elements but not all in javascript

const
divver = document.querySelector('div.divver')
, ShuffleDivs = divver.querySelectorAll('div.div') // just select this group
;
document.querySelector('button#shuffles').onclick = () =>
{
for (let i = ShuffleDivs.length; i >= 0; i--)
{
divver.appendChild(ShuffleDivs[Math.random() * i | 0])
}
}
<div class="divver">
<div class="extra"> Extra </div>
<div class="div"> 1 </div>
<div class="div"> 2 </div>
<div class="div"> 3 </div>
<div class="div"> 4 </div>
<div class="div"> 5 </div>
</div>

<button id="shuffles">Shuffle 'em</button>

How to randomly order two synchronized lists using javascript?

Get length of items and loop through it and in loop generate random number and using generated number select an li and append it end of parent.

var ul = document.querySelectorAll("ul");var length = ul[0].querySelectorAll("li").length;
for (var i=0; i<length; i++){ var rand = Math.floor(Math.random()*(length)); ul.forEach(function(ele){ ele.appendChild(ele.querySelectorAll("li")[rand]); });}
<ul>  <li>First title</li>  <li>Second Title</li>  <li>Thrid title</li></ul><ul>  <li>First text</li>  <li>Second text</li>  <li>Thhird text</li></ul>

Order by random a list of div elements with JS

The ideal way to shuffle the categories is through the backend. But incase you can't, we can borrow the shuffle functionality here.

Use jQuery get() to get the array of category divs. Use the function to shuffle the array and use html() to update the content.

function shuffle(array) {  var currentIndex = array.length,    temporaryValue, randomIndex;
// While there remain elements to shuffle... while (0 !== currentIndex) {
// Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1;
// And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; }
return array;}
var categories = shuffle($(".container-category>div").get());$(".container-category").html(categories);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div class="container-category">  <div class="col-3">item 1</div>  <div class="col-3">item 2</div>  <div class="col-3">item 3</div>  <div class="col-3">item 4</div></div>


Related Topics



Leave a reply



Submit