mardi 16 mai 2023

How to re-order and randomize DIVs using JavaScript

Long time reader, first time poster.

I was hoping someone might be able to help with this problem, which should be quite simple but unfortunately has me stumped. I'm trying to have a number of DIVs show up on page load but appear in a random order each time – but not entirely random as I'd like them to abide by some rules.

There are two different types of DIVs:

  1. Cards x5 (C)
  2. Image x4 (I)

The rules should be as follows:

  1. The first DIV must always be a C type
  2. Remaining DIVs should alternate between I and C (e.g. C, I, C, I, C, I, C, I, C)
  3. All DIVs should be randomly selected from their respective type/array

I've tried an array shuffle using jquery from the solution to another problem (below), but that just puts the DIVs in a random order, not taking into account rules 1 and 2.

var $cont = $('#content'),
  itemsArr = $cont.children().get();

$cont.append(shuffle(itemsArr))

function shuffle(a) {
    var j, x, i;
    for (i = a.length; i; i--) {
        j = Math.floor(Math.random() * i);
        x = a[i - 1];
        a[i - 1] = a[j];
        a[j] = x;
    }
    return a;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row" id="content">
  <div class="col-sm-12 col-md-6 col-lg-4" id="card1">Card #1</div>
  <div class="col-sm-12 col-md-6 col-lg-4" id="card2">Card #2</div>
  <div class="col-sm-12 col-md-6 col-lg-4" id="card3">Card #3</div>
  <div class="col-sm-12 col-md-6 col-lg-4" id="card4">Card #4</div>
  <div class="col-sm-12 col-md-6 col-lg-4" id="card5">Card #5</div>
  <div class="col-sm-12 col-md-6 col-lg-4" id="image1">Image #1</div>
  <div class="col-sm-12 col-md-6 col-lg-4" id="image2">Image #2</div>
  <div class="col-sm-12 col-md-6 col-lg-4" id="image3">Image #3</div>
  <div class="col-sm-12 col-md-6 col-lg-4" id="image4">Image #4</div>
</div>

Would be eternally grateful for any suggestions or help to point me in the right direction. Thanks in advance!




Aucun commentaire:

Enregistrer un commentaire