Skip to content Skip to sidebar Skip to footer

Adding A Random Class To Element From An Array That Duplicates Using Jquery

I'm creating a matching game and I'm trying to add a class from an array to match against. The code I have below creates the classes I need, then randomizes them. My problem is in

Solution 1:

I think your createDeck function needs to create 12 classes instead of 6. Just push each one twice:

function createDeck() {
    for (i = 1; i <= 6; i++) {
        cardDeck.push("card-" + i);
        cardDeck.push("card-" + i);
    }
}

Then you'll have an array of 12 classes (2 each of 6 unique classes), which will be randomized and assigned to the 12 cards.

Solution 2:

I suggest a separate variable to keep track of the index, rather that the each index. Once you've gone through the pack once, it might be a good idea to shuffle the deck again so the order is different on the second pass. YMMV.

functionsortCards(randOrd) {
  randDeck = cardDeck.sort(randOrd);
}

functionrandomizeDeck() {
  var count = 0;
  cards.each(function(i) {
    if (i === 6) { count = 0; sortCards(randOrd); }
    $(this).addClass(randDeck[count]);
    count++;
  });
}

Solution 3:

Your randomizeDeck() function can be rewritten to use the same array of class names twice:

functionrandomizeDeck() {
    card.each(function(i){
        if(i < 6)
            $(this).addClass(randDeck[i])
        else
            $(this).addClass(randDeck[i-6]);
    });
}

Note: I would rewrite the variable card as $cards so that you know it's a jQuery object and in this case a collection of them. Otherwise, its hard to tell it apart from any other javascript var.

Solution 4:

Try something like this - it's tested now updated SEE THIS FIDDLE http://jsfiddle.net/8XBM2/1/

var cardDeck = newArray();

functioncreateDeck() {
    for (i = 1; i <= 6; i++) {
        cardDeck.push("card-" + i);
    }
}
createDeck();
var randDeck = cardDeck.sort();
alert(randDeck);

functionrandomizeDeck() {
    var x = 0;
    $('div').each(function(i){
     if ( i > 5) { 

                $(this).addClass(randDeck[x]);
         x++; 
      } else {
        $(this).addClass(randDeck[i]);
    }
    });
}
randomizeDeck();

Post a Comment for "Adding A Random Class To Element From An Array That Duplicates Using Jquery"