I’m trying to create a game of memory using Javascript/jQuery. Basically, a random array is generated at the beginning of each game, and the user’s task is to match sets of letters. I’m having trouble selecting individual letters from the array.
Here’s a link to a working example on jsfiddle, but the relevant parts are below:
Here’s the html that the array is inserted into:
<div id="game"></div>
Right now, I’m just trying to implement a hover function that changes the background color of the letter. Here’s the CSS:
.hover
{
background-color: #A6977B;
}
Here’s the Javascript that generates the array:
function generateBoxes(gameSize, lettersSize) {
var currentLetter;
letters = randomizeArray(lettersSize);
rows = gameSize/columns;
for (var i=0; i<rows; i++) {
var row = $("<div class='row'></div>");
$("#game").append(row);
for (var n=0; n<columns; n++) {
currentLetter = letters[5*i + n];
row.append("<div class='column displayNone' id = 'r" + i + "c" + n + "'>" + currentLetter + "</div>");
}
}
};
Here’s the Javascript for the hover function:
$("#game").hover(function() {
$(this).toggleClass("hover");
});
This Javascript code for the hover function works to select all the letters within the array. I only want to select one at a time, however. I’ve tried replacing #game with:
#game div#game .row .column.column
None of those options work to select just one letter (in fact, when I use anything besides just #game, the hover function isn’t called at all).
What is the correct way to select child divs by class here?
Edit: Here is the generated html:
<div id="game">
<div class="row">
<div class="column displayNone" id="r0c0">E</div>
<div class="column displayNone" id="r0c1">D</div>
<div class="column displayNone" id="r0c2">E</div>
<div class="column displayNone" id="r0c3">D</div>
<div class="column displayNone" id="r0c4">B</div>
</div>
<div class="row">
<div class="column displayNone" id="r1c0">A</div>
<div class="column displayNone" id="r1c1">C</div>
<div class="column displayNone" id="r1c2">C</div>
<div class="column displayNone" id="r1c3">A</div>
<div class="column displayNone" id="r1c4">B</div>
</div>
</div>
Since you’re generating your letter divs dynamically, you’ll want to bind the mouseenter and mouseleave events to the divs using jQuery’s .on() function. Try this: