0

This code works great for me but I need the two variables inside the listener to be dynamic numbers representative of the item which you clicked. Right now of course they are hard coded to "7" but all I need is to make them dynamic.

var items = document.getElementsByClassName('largeItems');

for (var i = 0; i < items.length; i++) {
    items[i].addEventListener('click', function() {
        var itemWays = 7;
        var currentItem = 7;
        document.getElementById('display').src = detailsImage[itemWays];
    }, false);
}

I guess I would like something like this:

var itemWays = this.items[i]; //this.itemIndex that was clicked
var currentItem = this.items[i]; //this.itemIndex that was clicked

Cheers,

bo_
  • 188
  • 1
  • 8
  • If I had a dollar for every "my loop and closure doesn't work". – Evan Trimboli Nov 08 '13 at 09:59
  • possible duplicate of [Event handlers inside a Javascript loop - need a closure?](http://stackoverflow.com/questions/341723/event-handlers-inside-a-javascript-loop-need-a-closure) – Quentin Nov 08 '13 at 10:01

1 Answers1

1

The HTMLElement is this. The index i is a bit harder to capture, since it takes on a whole bunch of values during the for loop. Wrapping it in a function to "save" its value will work.

var items = document.getElementsByClassName('largeItems');

for (var i = 0; i < items.length; i++) {
    (function(i) {
        items[i].addEventListener('click', function() {
            var itemWays = i;
            var currentItem = this;
            document.getElementById('display').src = detailsImage[itemWays];
        }, false);
    })(i);
}

If you are not using IE8 or below, do

Array.prototype.forEach.call(document.getElementsByClassName('largeItems'), function(item, i) {
    item.addEventListener('click', function() {
        var itemWays = i;
        var currentItem = this;
        document.getElementById('display').src = detailsImage[itemWays];
    });
}); 
Paul Draper
  • 78,542
  • 46
  • 206
  • 285