I'm still new to JavaScript and i'm having the below issue.
I'd like to name/declare my function and then use its name as listener to add/remove click events easily. the main reason for this is so I can remove the click events whenever some condition happens.
Brief of what i'm trying to achieve:
function game() {
//
}
The problem i'm having is when I add the event like this:
for (let i = 0; i < cards.length; i++) {
card = cards[i];
card.addEventListener('click', game);
}
I get an error with the named function game that says:
i is not defined
However, this error doesn't happen when I put the function as anonymous inside the listener parameter.
for (let i = 0; i < cards.length; i++) {
card = cards[i];
card.addEventListener('click', function game() {
//
}
Declaring i
globally didn't work nor passing i
as parameter.