2

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?

kukkuz
  • 41,512
  • 6
  • 59
  • 95
Magdi Gamal
  • 681
  • 1
  • 9
  • 25
  • The reason it is always showing 4 is because your loop always finishes before a click event happens, and when your loop finishes the value of `i` is 4. So I suggest you to create a promise type implementation, basically assign unique `id`s to every element yourself and after the click trigger, get the element id. – kaushik94 Aug 19 '17 at 23:20

1 Answers1

2

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'));
   });
}
Alejandro Iván
  • 3,969
  • 1
  • 21
  • 30