Will
Will

Reputation: 544

Javascript FOR Loop Callback

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));
};

Upvotes: 0

Views: 132

Answers (1)

gen_Eric
gen_Eric

Reputation: 227200

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));
}

Upvotes: 3

Related Questions