I am trying to make a matching card game to become better in js in which when you open two cards that match they disappear from the deck. I am populating a ul with the images from an array like so:
var masks = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "6.jpg", "7.jpg", "8.jpg", "1.jpg", "2.jpg", "3.jpg", "4.jpg", "6.jpg", "7.jpg", "8.jpg"];
for (var i = 0; i < masks.length; i++) {
$(".deck").append('<div class="card"> <img class="card" src="./' + masks[i] + '"/></div>');
}
})
Here is the ul that gets populated:
<ul class="deck" id="card-deck">
<li></li>
</ul>
When you click on two of them, they get displayed and stay opened until you click elsewhere, I want to make them disappear if they match if not they should close, how can that be achieved? What is the right way to approach and do this? I know I have to make each card unique for starters and probably store them in another array, but I dont know how to do that since they are generated dynamically.
Here is the function that hides and shows them:
$(document).ready(function () {
$(".deck").on('click', '.card', function () {
var cardVisible = $('.card img:visible').length; //Get the number of visible img
if (cardVisible >= 2) $('.card img').hide(); //If 2 or more, hide all
$(this).find("img").show(); //Show the image
});