Search code examples
jqueryhtmlcssflickity

Flickity Slideshow Caption and Slide number


I'm implementing a Flickity slideshow, which includes a Slide counter at the bottom, and slide caption at the top. I've got them both in however the Caption at the top won't display what should be the img alt tag.

This is what I have - JSfiddle

HTML :

<section class="ux-carousel">
  <div class="carousel">
  <div class="carousel-cell">
  <img class="carousel-cell-image" src="https://source.unsplash.com/5i8l46zW8do" alt="Image 01" width="1170" height="685" />
  </div>
  <div class="carousel-cell">
  <img class="carousel-cell-image" src="https://source.unsplash.com/5i8l46zW8do" alt="Image 01" width="1170" height="685" />
  </div>
  </div>
  <div class="carousel-counter">
  <p class="carousel-status"></p>
  </div>
  <div class="carousel-caption">
  <p class="caption">&nbsp;</p>
  </div>
  </section>

Jquery :

var flkty = new Flickity('.carousel', {
  imagesLoaded: true,
  percentPosition: false,
  pageDots: false
});
var carouselStatus = document.querySelector('.carousel-status');
var caption = document.querySelector('.caption');

function updateStatus() {
  var slideNumber = flkty.selectedIndex + 1;
  carouselStatus.textContent = slideNumber + '/' + flkty.slides.length;
}
flkty.on( 'select', function() {
  // set image caption using img's alt
  caption.textContent = flkty.selectedElement.alt;
});
updateStatus();

flkty.on( 'select', updateStatus );

Solution

  • Very close, you're just handling the flkty object incorrectly; the context of flkty.selectedElement is not the <img> element, it's the entire slide meaning the element <div class="carousel-cell">.

    As such, the alt property doesn't exist and so there's nothing to set the caption to. You could make this more dynamic to say locate the img within the slide markup, filter by class, etc but if you know your slide content markup structure will remain the same, the simplest solution is to just grab the alt value from the first child element within the slide.

    So your on select function becomes:

    flkty.on( 'select', function() {
      caption.textContent = flkty.selectedElement.children[0].alt;
    });
    

    Because .children returns an array of the HTML elements within the context set (e.g. the children of flkty.selectedElement), we can use the array index notation to grab the first element (e.g. array index 0), which in your markup is the <img> and then access its alt as desired.

    Working jsFiddle here: https://jsfiddle.net/b5jr2L0d/3/