Casper van Sligtenhorst Casper van Sligtenhorst - 6 months ago 9
Javascript Question

Execute action after an element is clicked twice

For school we need to make a memory game. We're at the point that we have the cards and you can sort them. But now we need to check if 2 elements are clicked, and then execute an action. All the div's have an unique Id and a same class. I know you can do it for one element with .click, but I was wondering whether you can do something like that for 2 elements.

Thanks in advance.

Answer

If, every time a card is clicked, you indicate that it has been clicked, and then count the number of cards that have that indicator, you can determine whether or not to run the additional logic. Assuming your cards each have a class "card" to indicate that the elements are cards, the code would look something like this:

$('.card').click(function(e) {
    $(this).addClass('clicked'); // indicate that this card has been clicked
    // any other logic run every time a card is clicked, such as turning it face up
    if($('.card.clicked').length === 2) { // query all .card.clicked elements, and compare the length (number of matched elements) to 2
        // run logic if two cards have been clicked
        $('.card.clicked').removeClass('clicked'); // clear the "clicked" indicators
    }
});
Comments