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,
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];
});
});
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments