0

I'm trying to create a single function that works for multiple selections. I'm creating a selection screen of a video game that should work like this: https://oege.ie.hva.nl/~meestej005/eind/

The way I achieved this was with this code:

function character1(){
for (var i = 0; i < sprite.length; i++){
    sprite[i].classList.remove('charSprite');
}
sprite[0].classList.add('charSprite');
hadouken.play();
}

I made this function 4 times, one for each character. They are called with this:

char1.addEventListener('click', character1);

Right now, I want to create a function that does this for each character. This is what I came up with:

function character(name, music){
for (var i = 0; i < sprite.length; i++){
    sprite[i].classList.remove('charSprite');
}
name.classList.add('charSprite');
music.play();
}

char1.addEventListener('click', character(charSprite1, hadouken));

Sadly, this doens't work. Clicking one of the characters now results into absolutely nothing, not even an error. So I'm doing something wrong, but have no idea what. I want to fix this using only Javascript. I hope you guys can help me out. Thanks.

gyre
  • 16,369
  • 3
  • 37
  • 47
H0ndman2
  • 41
  • 2
  • 8

1 Answers1

1

addEventListener takes a function as its second argument. When you invoke the function like character(charSprite1, hadouken), you are no longer passing that function reference around (instead, you are passing the result of that function, which is being called immediately rather than when an event fires). I would suggest capturing the name and music arguments using closure, and returning a function each time from character:

function character(name, music) {
  return function() {
    for (var i = 0; i < sprite.length; i++) {
      sprite[i].classList.remove('charSprite');
    }
    name.classList.add('charSprite');
    music.play();
  }
}

char1.addEventListener('click', character(charSprite1, hadouken));
gyre
  • 16,369
  • 3
  • 37
  • 47
  • I'm beginning to understand more how this works, thanks. But what do you mean by closure? And what function should I return? – H0ndman2 Apr 09 '17 at 20:19
  • Read more about closure [here](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work#111111). `return function` in the code I posted above is the part of this solution that allows you to "capture" `name` and `music`. – gyre Apr 09 '17 at 20:37
  • Perhaps an easier alternative would be to pass a binding. – Raymond Chen Apr 09 '17 at 20:50
  • @RaymondChen `bind` can get ugly if you ever end up wanting to use `this`, but I see your point. – gyre Apr 09 '17 at 20:51