Nihil
September 24, 2022, 10:30am
1
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!
texnixe
September 24, 2022, 10:38am
2
Yes, and no need for the if statement
Note that the index starts with 0, so you need to add 1.
Nihil
September 24, 2022, 10:46am
3
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 …
texnixe
September 24, 2022, 10:57am
4
Pass the $gallery variable as argument to indexOf()
texnixe
September 24, 2022, 11:02am
6
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