Image counter in slideshow

Hello everyone,

I have a slideshow and want to display a counter (Image X of Y). This is what I came up with:

<?php foreach ($gallery as $image): ?>
	<?php if($image->isFirst($gallery) === true): ?>
		<figure class="slide visible">
			<img src="<?= $image->url() ?>">
			<figcaption>
				<p><?= $image->caption() ?></p>
			</figcaption>
			<div class="counter visible">
				<p>Image 1 of <?= $gallery->count() ?></p>
			</div>
		</figure>
	<?php else: ?>
		<figure class="slide">
			<img src="<?= $image->url() ?>">
			<figcaption>
				<p><?= $image->caption() ?></p>
			</figcaption>
			<div class="counter visible">
				<p>Image <?= $image->sort() ?> of <?= $gallery->count() ?></p>
			</div>
		</figure>
	<?php endif ?>
<?php endforeach ?>

It works OK, but only if the image collection remains untouched. If an image is deleted manually, the Sort field won’t be updated, and the counter gets mixed up.

Is there a more elegant solution?

Many thanks!

Yes, and no need for the if statement

Note that the index starts with 0, so you need to add 1.

Thanks texnixe,

I thought of indexOf(), too — however, if the images are sorted arbitrarily in the panel, the counter doesn’t really work anymore. I.e., it might start with 2/3, then display 1/3, then 3/3.

no need for the if statement

This is my clumsy attempt at assigning the “visible” class to the first image in order for the slideshow to work …

Pass the $gallery variable as argument to indexOf()

Thank you!

And regarding the the if statement for the class: You only need it for the class then and don’t have to repeat the complete HTML.

<?php foreach ($gallery as $image): ?>

		<figure class="slide <?= $image->isFirst($gallery) ? 'visible' : '' ?>">
			<img src="<?= $image->url() ?>">
			<figcaption>
				<p><?= $image->caption() ?></p>
			</figcaption>
			<div class="counter visible">
				<p>Image <?= $image->indexOf($gallery) + 1 ?> of <?= $gallery->count() ?></p>
			</div>
		</figure>

<?php endforeach ?>
1 Like