0

I have 10 divs, with id's key0, key1, key2, etc. In my initialize function I was trying to run a loop to add event handlers to all of them, like so:

for (x=0; x<=9; x++){
    document.getElementById("key" + x).addEventListener("click", function(){ numClick(x) }, false);
}

The goal being to set up each div with an event that would send the corresponding number to the numClick function when it was clicked. I mistakenly expected it to set the value of the variable when the event handler was assigned, but of course it doesn't. So every time one of the divs is clicked it always sends a value of 10, since that is what x ends up at after the loop.

I've been trying to figure out a way to make this work but so far I haven't come up with anything.

  • so your problem is in ("key" + x) . right? – King of kings Apr 02 '14 at 07:38
  • @Soombinakundi: No, that is executed in the loop itself. The problem is `numClick(x)` as that is executed by the event handler some time after the loop has ended. – Guffa Apr 02 '14 at 07:39
  • no the ("key" + x) works fine. it's the numClick(x) that's the problem. because at the time the divs are clicked, the loop has run in it's entirety and x = 10. – SometimesDirty Apr 02 '14 at 07:40
  • I just want to suggest you a different approach. Not sure if you like it, though: http://jsfiddle.net/LgyxY/ – Timo Virkkunen Apr 02 '14 at 07:44
  • @TimoVirkkunen I'll be honest, I don't really understand what's going on in your fiddle, I'm still very much learning. But it looks interesting so I'm going to spend some time figuring it out. – SometimesDirty Apr 02 '14 at 07:50
  • It's ok :) I try to explain it: first the code finds all HTML elements which belong to class `key`. That's the `class="key"` in the HTML. Then it will loop through all these elements and adds the `eventListener` to them and gets the function argument value from the element's attribute declared in HTML with `data-key=[VALUE]`. – Timo Virkkunen Apr 02 '14 at 07:58
  • Thanks for the help Timo. I've pretty much been able to figure out what all the code does. The only line that's giving me trouble is this: var keys = Array.prototype.slice.call(document.getElementsByClassName("key")); I understand what the end result is, keys ends up being an array that contains every element with class="key", but I don't understand HOW it's doing it. I haven't worked with arrays that much, I don't know any of those array methods, so I'm going to have to look at those. – SometimesDirty Apr 02 '14 at 08:09

1 Answers1

1

Use an immediately executed function expression inside the loop, that will create a scope for each iteration where you can have a variable instance:

for (x=0; x<=9; x++){
  (function(y){
    document.getElementById("key" + y).addEventListener("click", function(){ numClick(y) }, false);
  })(x);
}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005