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:
- Cards x5 (C)
- Image x4 (I)
The rules should be as follows:
- The first DIV must always be a C type
- Remaining DIVs should alternate between I and C
(e.g. C, I, C, I, C, I, C, I, C) - 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.
3
Answers
shuffledCards
andshuffledImages
Then, combine the two lists one by one by the
shouldTakeCard
response, for exampleSo you will start by C type, as
shouldTakeCard
initialized with C. then it will pick I, C, I … until the array are empty.One cation here is the length of the arrays that should be
shuffledCards.length === shuffledImages.length + 1
Rough idea is to remove the elements from DOM, shuffle them and append to original parent:
Here is a non-JQuery example with some comment. By the way: in your html
div#image5
is missing …