JSFiddle - React, Tailwind, and code Playground
HTML
<div id="memory_board"></div>
<script>newBoard();</script>
CSS
div#memory_board{
background: #CCC;
border: #999 1px solid;
width: 600px;
height: 500px;
padding 24px;
margin: 0px auto;
}
div#memory_board > div{
background: #00f;
border: #000 1px solid;
width: 71px;
height: 71px;
float: left;
margin: 10px;
padding 20px;
font-size: 64px;
cursor: pointer;
text-align: center;
}
JavaScript
var memory_array = ['A','A','B','B','C','C','D','D','E','E','F','F','G','G']; //holds content hiding under cards
var memory_value = []; //storing memory values
var memory_tile_ids = []; //storing memory tile ids
var tiles_flipped = 0; //keeping track on how many tiles are flipped
//add shuffle method to array object
Array.prototype.memory_tile_shuffle = function(){ //use prototype-property to add directly to all array-objects
var i = this.lenght, j, temp; //Variables: i = array-length; j, temp
while(--i > 0){
j = Math.floor(Math.random() * (i+1)); //choosing a random position j in array
temp = this[j]; //storing value of position j
this[j] = this[i]; //switching value of position j with value of position i
this[i] = temp; //replacing value of position i with value from temp (value @pos_j)
}
}
//function for generating a new board
function newBoard(){
tiles_flipped = 0; //starting with no flipped tiles
var output = ''; //create empty variable
memory_array.memory_tile_shuffle(); //calling shuffle function for memory_array to get new arrangement for tiles each time
for(var i = 0; i < memory_array.lenght; i++){ //looping over all of the cards
output += '<div id="tile_'+i+'" onclick="memoryFlipTile(this,\''+memory_array[i]+'\')"></div>'; //add all the divs to output-variable
//every div gets an id with dynamic tile_number; each div gets an onclick-event: new function called memoryFlipTile with 2 variables/arguments -> this=whichever div is being accessed + data for the cards(content of array at specific position)
}
document.getElementById('memory_board').innerHTML = output; //put output in memory_board
}