0

Currently working on a piece of code that is supposed to add eventlisteners to images on a page in a dynamical way.

var images = document.getElementsByClassName("imageBox");

function imageZoomer(imageName) {
    console.log(imageName);
}

for(var i = 0; i < images.length; i++) {
    images[i].addEventListener("click", function(){imageZoomer(i)}, false);
}

However the i is showing different values then I expect. At first everything is going wel. It iterates just like it's suppose to do. But on my test page with 2 images the console log reveals '2' at both the images.

Kipt Scriddy
  • 743
  • 2
  • 14
  • 22

1 Answers1

0

This happens because i keeps incrementing and by the time you click an image i is probably images.length - 1. You need a way to save the current i in each handler. You can store that value on each image (images[i].index = i; usually works) and retrieve it later but finding the object is a pain - it'd end up being something like:

images[i].index = i;
images[i].addEventListener("click", function(e){imageZoomer(e.target.index)}, false);

However, I've found the slickest way to do this is using an IIFE (read: iffy - Immediately Invoked Function Expression) to restrict the scope of i to whatever it was when the event was created. That looks something like:

images[i].addEventListener("click", (function(i){return function(){imageZoomer(i)}})(i))

IIFEs are super powerful. Take a look at Ben Alman's post: http://benalman.com/news/2010/11/immediately-invoked-function-expression/

Brin Marx
  • 143
  • 5
  • _"by the time you click an image `i` is probably `images.length - 1`"_ - No, it'll be `images.length`. Either way, do you really think a new answer was necessary when there are already three duplicate questions linked above? – nnnnnn Nov 30 '13 at 01:34