Magdi Gamal Magdi Gamal - 1 month ago 15
Javascript Question

Return index of clicked element in an array and make that the value of a variable outside?

Ok so this my code right now:

(function slideshow(){

var arr = [first, second, third, forth];
for( var i = 0; i < arr.length; i++){
arr[i].addEventListener('click', function(){
alert(i);
});
}

var d = 0;

}());


What I've been trying to do for the last hour and failing miserably, is for
i
to be the index of the clicked element in the array. Right now
alert(i)
always return
4
instead of the index number of the clicked element.

The other thing I want to happen is to have that value (the indexOf the clicked element) to become the value of
d
, which is outside the for loop.

ie.
d=0
by default until you click
arr[i]
then
d = i
. Any ideas how I'd go about doing that?

Answer Source

This is because i is the value that i has after the for loop. 0 to 3 are your indexes and 4 is the value that exited of the loop because it's larger than your array length.

What you need to do is to actually have a value stored in first, second, etc. that you can grab.

You could store the actual value of i inside the element:

var arr = [first, second, third, forth];
for( var i = 0; i < arr.length; i++){
   arr[i].setAttribute('data-index', i);
   arr[i].addEventListener('click', function(){
      alert(this.getAttribute('data-index'));
   });
}