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,

2

1 Answer 1

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];
    });
}); 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.