Magdi Gamal Magdi Gamal - 7 months ago 40
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(){

var d = 0;


What I've been trying to do for the last hour and failing miserably, is for
to be the index of the clicked element in the array. Right now
always return
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
, which is outside the for loop.

by default until you click
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(){
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download