I have a Photoswipe Lightbox applied to a SwiperJS gallery, and I would like to add a button outside the lightbox-wrapper, that opens the first image, no matter what the current visible image is.
Here's the code that populates the gallery and applies the lightbox:
<div class="swiper-wrapper lightbox">
<?php
$i = 0;
foreach( $gallery as $image_id ):
$i++?>
<?php $img_info = wp_get_attachment_image_src($image_id, 'full');?>
<a <?php if($i == 1) { echo 'x-ref="firstSlide"'; } ?> href="<?= wp_get_attachment_image_url( $image_id, $size ); ?>"
class="relative w-full h-full hover:cursor-pointer aspect-vertical swiper-slide"
data-pswp-width="<?= $img_info[1]; ?>"
data-pswp-height="<?= $img_info[2]; ?>"
target="_blank">
<?= wp_get_attachment_image( $image_id, $size_medium, false, array('class' => 'object-cover w-full h-full ' . $rounded_elements)); ?>
</a>
<?php endforeach; ?>
</div>
And here's the button that I'd like to trigger the opening of the first image:
<button class="absolute z-50 bottom-12 right-12 flex items-center justify-center opacity-80 hover:opacity-100 transition w-10 h-10 bg-white <?= $rounded_buttons; ?> shadow-md md:w-14 md:h-14 text-primary-dark">
<i class="icon-resize-full-alt"></i>
</button>
This answer is based on this Github-issue and adapted for AlpineJS.
This can be solved by using
x-refandx-on:click(or@click).Start by adding an empty x-data to the gallery wrapper:
We can now target the wrapper with Alpine and do whatever we want with it. After this, add an
$i = 0;just before theforeach. Just after yourforeach, you add$i++so the $i-variable gets updated for each loop. Now, on youra-element, you add anx-refby checking if the$iis 1.This will add
x-ref=firstSlideto, well, the first slide.After that, we can adapt the button to target that specific
x-refby adding the following:@click="$refs.firstSlide.click()"This will click on the element with the x-ref
firstSlide.Here's the complete code: