Home > Net >  Randomize order of <div>s or <li>s with pure JS on page load
Randomize order of <div>s or <li>s with pure JS on page load

Time:01-25

I saw multiple answers to randomize the order of <div> (or <li>s or whatever) using jQuery, but how do I do this using pure javascript?

<ul id="wrapper">
  <li>Answer 1</li>
  <li>Answer 2</li>
  <li>Answer 3</li>
</ul>

CodePudding user response:

Randomly shuffle an array of cloned li elements and replace original with the new ones:

For the shuffleFisherYates function see

function reOrderListItemsRandomly(ulId) {
  const ul = document.querySelector(`ul#${ulId}`);
  const liElems = ul.querySelectorAll(`li`);

  // create new array with cloned li elements and shuffle it
  const nwLiElems = shuffleFisherYates([...liElems]
    .map(li => li.cloneNode(true)));

  // replace the old li with the corresponding li from the 
  // array of new elements, see also
  // https://developer.mozilla.org/en-US/docs/Web/API/Element/replaceWith
  [...liElems].forEach( (li, i) => li.replaceWith(nwLiElems[i]) );

  // see https://stackoverflow.com/a/49555388/58186
  function shuffleFisherYates(array) {
    let i = array.length;
    while (i--) {
      const ri = Math.floor(Math.random() * i);
      [array[i], array[ri]] = [array[ri], array[i]];
    }
    return array;
  }
}

// button handling
document.addEventListener(`click`, handle);

function handle(evt) {
  if (evt.target.id === `shuffle`) {
    return reOrderListItemsRandomly(`wrapper`);
  }
}
<ul id="wrapper">
  <li>Answer 1</li>
  <li>Answer 2</li>
  <li>Answer 3</li>
  <li>Answer 4</li>
  <li>Answer 5</li>
  <li>Answer 6</li>
</ul>
<button id="shuffle">shuffle answers</button>

CodePudding user response:

Here my solution:

(function() {
  var wrapper = document.getElementById("wrapper");

  Array.from(wrapper.children)
    .sort((a, b) => 0.5 - Math.random())
    .forEach(node => {
      wrapper.removeChild(node);
      wrapper.appendChild(node);
    })
})()

First it takes the children of the wrapper and converts them to an Array using Array.from. Then we "sort" the Array by a random factor and then we call forEach on the array and remove from the element and add it again to the end of the wrapper. Since we randomized the array before, the result will be a random order of these elements.

  • Related