Displaying Swiper Images in a Lightbox

Using SwiperJS, you can easily create a fslightbox to display images. Let mesa show joe:

First make sure you have the swiper and fslightbox packages installed:

npm install swiper lightbox2

I have script running that checks whether swiper is needed, if so load the stuff.

// 11
import Swiper from "swiper";
import {
Navigation,
} from "swiper/modules";
// import Swiper and modules styles
import "swiper/css";
import "swiper/css/navigation";


function swiperInitialize(scope: Document | HTMLElement): void {
// Basic swiper element
if (scope.querySelector(".swiper-element")) {
new Swiper(".swiper-element", {
modules: [Navigation],
slidesPerView: 1,
navigation: {
prevEl: ".swiper-button-prev",
nextEl: ".swiper-button-next",
},
});
}
}

export { swiperInitialize };

Let me show you my html, notice the svg 'symbol' usage. Love this svg stuff!

{%- comment -%}
SVG Includes, this allows for using symbols like so:
<svg><use href="#id"></use></svg>
{%- endcomment -%}
<svg height="0" width="0" style="position: absolute;" xmlns="http://www.w3.org/2000/svg">
<symbol id="svg_lightbox_open" viewBox="0 0 24 24">
<path d="m0 0h24v24h-24z" fill="none"/>
<path d="m15 3 2.3 2.3-2.89 2.87 1.42 1.42 2.87-2.89 2.3 2.3v-6zm-12 6 2.3-2.3 2.87 2.89 1.42-1.42-2.89-2.87 2.3-2.3h-6zm6 12-2.3-2.3 2.89-2.87-1.42-1.42-2.87 2.89-2.3-2.3v6zm12-6-2.3 2.3-2.87-2.89-1.42 1.42 2.89 2.87-2.3 2.3h6z"/>
</symbol>
</svg>

<!-- Slider main container -->
<div class="swiper">
<!-- Additional required wrapper -->
<div class="swiper-wrapper">
<!-- Slides -->
<div class="swiper-slide">
Slide 1
<a class="lightbox-expand"
data-fslightbox="sid_{{ swiper.id }}"
data-type="image" href="{{ image | img_url: 1920, height: 1080, mode: 'fit' }}">

<span class="visually-hidden">Open</span>
<svg aria-hidden="true"><use href="#svg_lightbox_open"></use></svg>
</a>
</div>
</div>

<!-- If we need navigation buttons -->
<div class="swiper-button-prev"></div>
<div class="swiper-button-next"></div>
</div>

With the lightbox hyperlink in place on every swiper slide and a data-fslightbox attribute, you can now open the image in a lightbox and the images will be grouped 'per' swiper instance.

Neat right?

The following CSS will style the lightbox expand button, I've positioned it bottom right.

.lightbox-expand {
display: flex;
color: var(--primary-color);

position: absolute;
right: 1rem;
bottom: 1rem;
z-index: 1;
transition: transform .3s ease-in-out, opacity .3s ease-in-out;
opacity: .8;
transform: scale(.8);
&:hover {
transform: scale(1);
opacity: 1;
}
svg {
fill: currentColor;
width: 3rem;
height: 3rem;
}
}

And not to forget to load lightbox, as of now it's done via a require statement in my main script file.

require("fslightbox");

Et voila, that's all there is to it. Enjoy your lightbox images with SwiperJS!