1

I'm using Wordpress and ACF flexible-layouts to create Flickity image galleries.

I have 2 issues:

  1. How do i count the number of slides in the gallery. ( I want to only run Flickity if there are greater than 2 slides )
  2. How to run multiple galleries on the same post. ( each have the same class name )

I would like to use the nuSkool Vanilla JS option for this. See docs: http://flickity.metafizzy.co/#initialize-with-vanilla-javascript

PHP

<div class="gallery-slider flickity">
  <?php $i = 0; if(get_sub_field('gallery')): while(has_sub_field('gallery')): ?>
    <?php $attachment = get_sub_field('images');  ?>
    <img class="slide" src="<?php echo $attachment['sizes']['800cropped']; ?>" alt="<?php echo $attachment['alt']; ?>">
  <?php $i++; endwhile; endif; ?>
</div>

Vanilla JS

'use strict'
const Flickity = require('flickity')
const galleries = document.querySelector('.gallery-slider') 
 if (galleries) {
   const gallery = new Flickity( galleries, {
   setGallerySize: true,
   wrapAround: true,
   pageDots: true,
   prevNextButtons: true,
   autoPlay: 10000,
   imagesLoaded: true,
 }
)}

Current status, the code is working with one gallery per post and has pageDots and prevNextButtons controls even if there is just one slide.

Any help would be great, thanks in advance :)

No jQuery responses please.

Frithir.com
  • 295
  • 2
  • 15

1 Answers1

1

Updated answer: Use Array.prototype.forEach.call rather than Array.from() for IE support.

See this discussion

const galleries = document.querySelectorAll('.gallery')

Array.prototype.forEach.call(galleries, (gallery) => {
  const slides = gallery.querySelectorAll('.slide')
  if(slides.length > 1){
    const gallerySlider = new Flickity( gallery, {
     setGallerySize: true,
     pageDots: true,
     prevNextButtons: true,
     autoPlay: 10000,
     imagesLoaded: true,
    })
  }
}) 

Updated Example on codepen


Original Answer: Use galleries.forEach() and an if statement to determine number of slides. Also, use Array.from() for old browser support.

const galleries = Array.from(document.querySelectorAll('.gallery-slider'))

galleries.forEach(gallery => {
  const slides = gallery.querySelectorAll('.slide')
  if(slides.length > 1){
    const gallerySlider = new Flickity( gallery, {
     setGallerySize: true,
     pageDots: true,
     prevNextButtons: true,
     autoPlay: 10000,
     imagesLoaded: true,
    })
  }
})

Example on codepen

Community
  • 1
  • 1
Jinksi
  • 71
  • 4