I am creating a memory game for a small project and my logic is as follows:
- click on the input field to choose with how many pairs would you like to play
- create divs with classes card1, card2 etc.
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!