Can't show and then hide cards in matching game


#1

I’m trying to allow the user to briefly show all the randomized cards for x seconds before the play timer begins. Failing.

I’ve had minor success with this (commented out in the Pen):

document.querySelector('.showCards').addEventListener('click', showAllCards);
function showAllCards() {
  let pix = document.querySelectorAll('img');
    pix[0].style.display = 'inline';
    // setTimeout(hide, showAllHide);
};

But, the one card I flip seems to also be selected within the game.


#3

To show all cards, you need to loop through all images as opposed to just the first one. Try this code:

function showAllCards() {
  let pix = document.querySelectorAll('img');
  
  for (var i = 0; i < pix.length; i++) {
    pix[i].style.display = 'inline';
  }
    //pix[0].style.display = 'inline';
  //setTimeout(hide, showAllHide);
};

With this code, clicking on Show Cards ends up showing all of the cards :slight_smile:


#4

Thanks. Just after posting my question I solved it without using a loop (a very long way around indeed!). For some reason, although I get what a loop is, I cannot seem to comprehend it in practice. I think that comparing my solution (sans loop) and yours (loop) will help me a great deal!


#5

What was your non-loop solution? Did you set a class value on the parent container element that maps to a style rule that adjusts the display property?


#6

It’s been a couple days but I think I set each image in the array to display.
pix[0].style.display = ‘inline’;
pix[1].style.display = ‘inline’;
pix[2].style.display = ‘inline’;
// etc.


#7

Glad that worked, but that is a lot of code to copy/paste. A loop may be a better option in such a case :stuck_out_tongue:


#8

Agreed. In fact, your answer (compared to my earlier solution) really helped me comprehend how a loop actually gets used. Thanks.


#9

Totally forgot about this. In case you are curious to a similar game I created in React a while ago, check this out: https://github.com/kirupa/kirupa/tree/master/reactjs/koncentration :slight_smile:


#10

Thanks!
Now I just have to learn React!
:tired_face: