2

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';

}
  • 1
    Firstly, I strongly recommend you use `let` & `const` to declare variables instead of `var`. Secondly, pass in the value of `i` which is the index in this case to the `openModal` function. And thirdly, please declare `j` as well, you are currently not declaring it and straight away initializing it. It may work, but it's bad coding practice. – Link Nov 28 '20 at 20:21
  • 1
    1. You are calling the function inside the loop so just change the () with a reference to that function preceded by return and 2) use `this` to refer to the specific html element being clicked. Also, when the openModel handler is called you are not accessing the **local** index inside the for loop... – rags2riches-prog Nov 28 '20 at 20:21

2 Answers2

2

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';
}
emi
  • 2,786
  • 1
  • 16
  • 24
  • Thank you very much I've learned with your help how to transform an array with some researches, then your method is much more simple to use, thank you very much. I succeed in renaming my photos because index begin at 0 :) –  Nov 28 '20 at 22:18
1

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.

Ivan V.
  • 7,593
  • 2
  • 36
  • 53