0

There's a list of items IDs gameIds[i]_container that are displayed in a FOR loop. On These are being displayed without a problem.

I want the console to log the item's gameIds[i] on that items click. I believe this is supposed to be accomplished with a callback, but currently nothing occurs when items are clicked on.

Please help!

Code:

//CLICKING ON GAMES
//Active Game - bring user to game
//Newly Invited Game - ask user to accept invite, then either bring to game or delete from players list
//Rematch Game - recreate previous game

//Function
function gameAccess(i) {
    //REMATCH GAME
        if (currentRound[i] == roundWinners[i].length && currentRound[i] != 0 && currentRound[i] == numberOfRounds[i]){
            console.log("You clicked " + gameIds[i]);
        }
        //NEWLY INVITED GAME
        if (currentRound[i] == 0 && currentUserId != creator[i]) {
            console.log("You clicked " + gameIds[i]);
        }
        //ACTIVE GAME
        else{
            console.log("You clicked " + gameIds[i]);
        }
}

//Callback
function gameAccessCallback(i){
    return function(){
        gameAccess(i);
    };
}

//Iterate Through
for (i = 0; i < numberOf; i++) {
    document.getElementById(gameIds[i] + "_container ").click(gameAccessCallback(i));
};
Will
  • 546
  • 5
  • 16
  • Your question mentions `gameIds[i]_container`, but that is not valid Javascript. – jfriend00 Dec 26 '14 at 21:08
  • Similar questions: http://stackoverflow.com/questions/8623088/undefined-indexes-in-array-after-asynchronous-requests/8623120#8623120 and http://stackoverflow.com/questions/18880895/why-when-i-add-a-bunch-of-event-listeners-in-a-loop-does-every-element-trigger/18880964#18880964 and http://stackoverflow.com/questions/21487187/why-is-the-loop-assigning-a-reference-of-the-last-index-element-to/21487254#21487254 and http://stackoverflow.com/questions/22273839/proper-code-for-a-for-loop-in-javascript/22273973#22273973 – jfriend00 Dec 26 '14 at 21:11
  • 1
    I don't think this is duplicate. His `gameAccessCallback` function solves the problem in those duplicates. He's just not binding the event properly. – gen_Eric Dec 26 '14 at 21:12

1 Answers1

3

The problem here is that you are doing document.getElementById(...).click(). DOMElements don't have a click method! jQuery does, but it doesn't look like you are using that here.

Try this:

for (i = 0; i < numberOf; i++) {
    document.getElementById(gameIds[i] + "_container ").addEventListener('click', gameAccessCallback(i));
}
gen_Eric
  • 223,194
  • 41
  • 299
  • 337