Swiper - markhowellsmead/helpers GitHub Wiki

Using SwiperJS for sliders/carousels

See https://swiperjs.com/swiper-api. Usage instructions for installing and using SwiperJS through NPM are at https://swiperjs.com/get-started#install-from-npm. The CSS is now loaded through JavaScript, so you don't need to add (S)CSS files to the SCSS structure. You do, however, need to load the CSS through the JS file.

Example with multiple swipers on the page

If the slider contains images of varying heights, set the slide width to fit-content using CSS.

import 'swiper/scss';
import 'swiper/scss/pagination';

import Swiper from 'swiper';
import { Pagination } from 'swiper/modules';

document.addEventListener('DOMContentLoaded', () => {
	const swipers = document.querySelectorAll('.wp-block-shp-must-use-image-carousel__container');

	if (!!swipers.length) {
		for (let i = 0; i < swipers.length; i++) {
			swipers[i].classList.add('wp-block-shp-must-use-image-carousel__container--entry-' + i);

			new Swiper('.wp-block-shp-must-use-image-carousel__container--entry-' + i, {
				modules: [Pagination],
				slidesPerView: 'auto',
				spaceBetween: 24,
				pagination: {
					el: swipers[i].querySelector('.swiper-pagination'),
					clickable: true,
				},
			});
		}
	}
});

Alternatives

  • Greensock
  • SplideJS (acccessible!)