0

so I'm quite new to Javascript, and I'm building a web matching game, and I have a 6 X 4 grid of boxes that are clickable. I want the grapic that is situated behind the box to pop out the top when I click on it.

The HTML elements of the box graphic are stored in an array as well as the characers (enemies).

Here's my code:

for(var i = 0; i < box.length; i++)
{
    box[i].style.cursor = "pointer";
    box[i].addEventListener("click", clickHandlerBox, false);

    function clickHandlerBox()
    {
        enemy[i].style.top = (enemy[i].style.top + 10) + 'px';
        clickBox.play();
    }
}

I know the answer is probably simple and staring me in the face, but any help would definitely be appreciated. Thanks!

Maerus
  • 113
  • 2
  • Since `clickHandlerBox` runs after the loop, `i` will always be `box.length` (see [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/q/750486/1529630)). And functions should be declared only at top level or immediately within another function. Otherwise it won't work in strict mode, and will behave unreliably in non-strict mode. – Oriol Jan 11 '15 at 02:33
  • thanks for your answer, I've adjusted my code and I believe the issue resides in matching up the position with the box with the position of the character. Thanks! – Maerus Jan 11 '15 at 02:54

0 Answers0