It is clear that there is a lot of repetitive code below...
var card0 = document.getElementById('c0');
var card1 = document.getElementById('c1');
var card2 = document.getElementById('c2');
var card3 = document.getElementById('c3');
var card4 = document.getElementById('c4');
var card5 = document.getElementById('c5');
var card6 = document.getElementById('c6');
var card7 = document.getElementById('c7');
var card8 = document.getElementById('c8');
var card9 = document.getElementById('c9');
var card10 = document.getElementById('c10');
var card11 = document.getElementById('c11');
card0.addEventListener("click", function() {revealCard(0); });
card1.addEventListener("click", function() {revealCard(1); });
card2.addEventListener("click", function() {revealCard(2); });
card3.addEventListener("click", function() {revealCard(3); });
card4.addEventListener("click", function() {revealCard(4); });
card5.addEventListener("click", function() {revealCard(5); });
card6.addEventListener("click", function() {revealCard(6); });
card7.addEventListener("click", function() {revealCard(7); });
card8.addEventListener("click", function() {revealCard(8); });
card9.addEventListener("click", function() {revealCard(9); });
card10.addEventListener("click", function() {revealCard(10); });
card11.addEventListener("click", function() {revealCard(11); });
Looking to optimize this code, I attempted to use a for loop:
var cards = [];
for(i=0; i<12; i++)
{
cards[i] = document.getElementById('c'+i);
cards[i].addEventListener("click", function() {revealCard(i); });
}
Unfortunately, the optimized version did not work as expected. Despite no errors being shown in the console, the functionality does not seem to be working correctly. Any suggestions or help would be greatly appreciated.