how to catch an index of an array that iterates (Javascript)

Viewed 52

I'm trying to get an index inside an array each time it iterates, but i only get the length of that array. How can I do ?

I've made a outside of other div in the HTML code, which each of them contains a photo with a little icon to open a modal, and so I want the image source of the modal outside change and get the value of that index (in the array with the small images) each time when I click on an image. Thank you very much for your help :) Here is my code :

for (var i = 0; i < zoom.length; i++)
{
    zoom[i].addEventListener('click', () => 
    {
        openModal();
    })
}

function openModal()
{
        j = i;
        image.src = './img/screenshotSite' + j + '.png';
        modal.style.display = 'block';
        document.getElementsByTagName('*')[0].style.overflow = 'hidden';

}
2 Answers

You can use forEach to loop over an array. This ensures the correct value of the index when passed as argument to openModal:

// I suppose this is an HTMLCollection, so need this to transform into an array
[...zoom]
  .forEach( (element, index) =>
    element.addEventListener('click', () => openModal(index) )
  );

function openModal(index)
{
  image.src = './img/screenshotSite' + index + '.png';
  modal.style.display = 'block';
  document.getElementsByTagName('*')[0].style.overflow = 'hidden';
}

Just switch for( var i=0 .... with for( let i=0 .... There is a difference between let and var regarding the scope. More info in this SO answer.

Related