So I have this HTML:
<ul class="deck">
<li class="card">
<i class="fa fa-diamond"></i>
</li>
.....(16 total list items here)
</ul>
And this javascript:
const arrayOfCards = $('.card');
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
while (currentIndex !== 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
shuffle(arrayOfCards);
That function takes the cards (it's a card memory game) and shuffles them, but it doesn't move around the cards...I need to somehow move the cards around, I don't know how to do it. Should I, instead of having that HTML, create the cards (list items) dynamically from jQuery or what? I'm really confused here.
You need to append the sorted array to the dom. What you are currently doing is only sorting an array that happens to contain elements but that sorted array doesn't automatically change the dom
Here's a very simple shuffle approach.
var $deck = $('.deck'),
$cards = $deck.children();
$('button').click(function() {
// sort the elements
$cards.sort(function() {return Math.random() - .5; });
// update dom with new sort
$deck.append($cards);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="deck">
<li class="card">1</li>
<li class="card">2</li>
<li class="card">3</li>
<li class="card">4</li>
<li class="card">5</li>
<li class="card">6</li>
<li class="card">7</li>
<li class="card">8</li>
<li class="card">9</li>
<li class="card">10</li>
</ul>
<button>Shuffle</button>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments