0

I am creating a memory game for a small project and my logic is as follows:

  1. click on the input field to choose with how many pairs would you like to play
  2. create divs with classes card1, card2 etc.
  3. clone divs and randomize their place in the array

    $(document).ready(function () {
        $(".button").click(function () {
    
    // create the cards
            $(".container").append("<div class='card1 cards'></div>") &&
    $(".card1").clone().appendTo(".container");
            $(".container").append("<div class='card2 cards'></div>") &&
    $(".card2").clone().appendTo(".container");
            $(".container").append("<div class='card3 cards'></div>") &&
    $(".card3").clone().appendTo(".container");
    
    // randomize cards in stack
            var cards = $(".cards");
            for (var i = 0; i < cards.length; i++) {
                var target = Math.floor(Math.random() * cards.length - 1) + 1;
                var target2 = Math.floor(Math.random() * cards.length - 1) + 1;
                var target3 = Math.floor(Math.random() * cards.length - 1) + 1;
                cards.eq(target).before(cards.eq(target2)).before(cards.eq(target3));
            }
        });
    });
    

I've created steps 2 and 3 and they work (see JSFiddle), now I want to hook the input up and set the class name of the div dynamically. I guess I would need an array and some dynamically created vars - I tried to do that following these suggestions: jQuery dynamically increment variable name inside a for-loop and How to create dynamic variables using jquery? but I couldn't make it work.

So please make me a suggestion - how would you do it? And bare in mind this is a project for beginners. Thank you!

Community
  • 1
  • 1
pres
  • 71
  • 10

1 Answers1

1

I added on to your fiddle: http://jsfiddle.net/007y4rju/1/

$(document).ready(function () {

    $(".button").click(function () {        
        // get the value from the input
        var numCards = parseInt($('input').val());

        for (var i = 1; i <= numCards; i++) {
            // create the cards
            $(".container").append("<div class='card" + i + " cards'></div>") &&
            $(".card" + i).clone().appendTo(".container");
        }

        // randomize cards in stack
        var cards = $(".cards");
        for (var i = 0; i < cards.length; i++) {
            var target = Math.floor(Math.random() * cards.length - 1) + 1;
            var target2 = Math.floor(Math.random() * cards.length - 1) + 1;
            var target3 = Math.floor(Math.random() * cards.length - 1) + 1;
            cards.eq(target).before(cards.eq(target2)).before(cards.eq(target3));
        }
    });
});

The basic idea is to get the number someone typed in (and turn it into a numer, as it will be a string otherwise), then loop through and dynamically create the class names. So "class='card" + i + " will become "class='card1'" and so on.

mherzig
  • 1,528
  • 14
  • 26