If current image is second image on page

Hi!

I’m trying to get the index number of the second uploaded image on a page.
My specific goal is to append a certain classname to the second image in a slideshow.
I can’t however get the if-statement in the foreach-loop right, where I’d ask “if this image is the second image of all uploaded images on this page”.
I tried combinations of filterby, first, last, next, prev, count and other selectors I found in the docs, with no success.

Can somebody point me in the right direction?

Thanks!

You can use indexOf():

<?php 
$images = $page->images();
foreach($images as $image):
  if ($images->indexOf($image) === 1):
    echo "Hey, I'm the second image of all images";
  endif;  
endforeach; 
?>
4 Likes

Alternatively, you could target the second image with CSS:
img:nth-child(2) { … }

While that is very true, it doesn’t help if you need a class name on the element itself…

Thanks texnixe, I’ll try your solution.
And thanks cadars for the hint, but yeah, I need to assign a class-name to the second image for lazy-preloading purposes.