I am working on an assignment where you create a Memory game with a 4x4 grid of divs to serve as cards. The end goal is a user selects two cards. If they are a match then remove them from the game (Change the colors to white so the card appears gone) and if they are not a match, turn them back into black. I am using console.logs as placeholders just to show that the functions run properly, but I am stuck on how to change the colors. Additionally, the original colors of the cards have to remain showing for two seconds before changing to white or black. I know that this requires the use of setInterval, but my main concern is changing the colors of the cards and having them change to the proper colors depending on if it is a match. This is what I have so far:
var elements = document.getElementsByClassName('grid-cell');
var i;
var picks = [];
//Event Listeners to respond to a click on the squares.
for (i = 0; i < elements.length; ++i) {
elements[i].addEventListener('click', showColor);
}
function showColor(){
this.style.backgroundColor = this.getAttribute('data-color');
picks.push(this.getAttribute('data-color'));
console.log(picks);
if(picks.length === 2){
checkMatch();
picks = [];
}
}
function checkMatch(){
if(picks[0] === picks[1]){
console.log("Match");
}else{
console.log("Not a match");
}
}
.grid-container {
display: grid;
grid-template-columns: repeat(4, 106.25px);
grid-gap: 15px;
}
.grid-cell {
height: 106.25px;
border-radius: 3px;
background: #000000;
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Memory</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="game-container">
<div class="grid-container">
<div class="grid-cell" data-color="red">
<span></span>
</div>
<div class="grid-cell" data-color="blue">
<span></span>
</div>
<div class="grid-cell" data-color="pink">
<span></span>
</div>
<div class="grid-cell" data-color="orange">
<span></span>
</div>
<div class="grid-cell" data-color="purple">
<span></span>
</div>
<div class="grid-cell" data-color="green">
<span></span>
</div>
<div class="grid-cell" data-color="yellow">
<span></span>
</div>
<div class="grid-cell" data-color="grey">
<span></span>
</div>
<div class="grid-cell" data-color="orange">
<span></span>
</div>
<div class="grid-cell" data-color="red">
<span></span>
</div>
<div class="grid-cell" data-color="green">
<span></span>
</div>
<div class="grid-cell" data-color="pink">
<span></span>
</div>
<div class="grid-cell" data-color="blue">
<span></span>
</div>
<div class="grid-cell" data-color="grey">
<span></span>
</div>
<div class="grid-cell" data-color="purple">
<span></span>
</div>
<div class="grid-cell" data-color="yellow">
<span></span>
</div>
</div>
</div>
<script src="js/app.js"></script>
</body>
</html>