Giving information to a image

I got a (maybe a bit silly) question. I’m making a photo gallery using javascript. I need to give every image some information (a id), so i can ask javascript what image is currently open.

Example:

I got a array of some images. Those images have a id 1, 2 and 3. When I’m using the gallery to slide through the images, I want to know what image Im looking at.

It can be done by giving the images alt the information I need. So I can go like;

var id = document.getElementById("image").alt;

But I though this wasn’t the way to do it. Is there a simple solution for this problem?

Answer

I assume you have multiple <img> elements. You could give each of them the same class value so you can easily get a reference to all of them. You could then use data- attributes for any data you want to assign to them.

<img class="gallery-image" data-id="1" ...
<img class="gallery-image" data-id="2" ...
<img class="gallery-image" data-id="3" ...

JavaScript

var images = document.getElementsByClassName('gallery-image');
for (var i = 0; i < images.length; i++) {
    var id = images[i].getAttribute('data-id');

    ...
}

Leave a Reply

Your email address will not be published. Required fields are marked *