Ad

Order By Random A List Of Div Elements With JS

- 1 answer

I have a category that contains more than 200 newsitems, on the homepage I display the last 20 newsitems.

<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 class="col-3">item ..n</div>
</div>

How to make the list of <div class="col-3"> appear randomly with Javascript ?

OrderBy = random

Ad

Answer

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>

Ad
source: stackoverflow.com
Ad