0

It would be easier to explain when you see the code first. Here is the HTML:

<img class="resizableImage" src="PATH">
<img class="resizableImage" src="PATH">

And here is the Javascript:

var img = document.getElementsByClassName("resizableImage");
img.onclick = function(){
//Do Stuff To The Image Clicked
}

The above script doesn't work, because the variable img is an array, so img.onclick doesn't work. I need to specify the index (like img[0].onclick). But how do I get the index of the image clicked?

I know I can put unique ids on every image, and check when each one is clicked, but some pages have 1 image, and some has 20. I want the script to be universal. No matter what image is clicked, the same function needs to be called. Can I get the index of the image clicked, store it in a variable, and use it in the above script? I highly prefer pure Javascript.

Thank you.

Cyber Shadow
  • 100
  • 1
  • 11

1 Answers1

1

Hope this helps you!

const imgs=document.querySelectorAll("img.resizableImage");
for(let i=0;i<imgs.length;i++){
  imgs[i].onclick=function(){
    alert( "My Index is : " + i );
  }
}
<img class="resizableImage" src="PATH">
<img class="resizableImage" src="PATH">
<img class="resizableImage" src="PATH">
Adnane Ar
  • 683
  • 7
  • 11