I can't seem to retrieve the image alt tag using JavaScript. Is it even possible and if so, how should I go about it?
Perhaps something like this: $caption.text( flkty.selectedElement ).attr('alt') (last line of JavaScript)
But I'm struggling to make it work...
Thanks!
var $carousel = $('.carousel').flickity({
imagesLoaded: true,
percentPosition: false
});
var $caption = $('.caption');
// Flickity instance
var flkty = $carousel.data('flickity');
$carousel.on( 'select.flickity', function() {
// set image caption using img's alt
$caption.text( flkty.selectedElement.alt )
});
.carousel-cell {
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.carousel-cell img {
max-width: 100%;
}
p {
text-align: center;
}
<link rel="stylesheet" href="https://unpkg.com/flickity@2/dist/flickity.min.css">
<div class="carousel">
<div class="carousel-cell>
<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/82/orange-tree.jpg" alt="orange tree" />
</div>
<div class="carousel-cell">
<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/82/submerged.jpg" alt="submerged" />
</div>
</div>
<p class="caption"> </p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/flickity@2/dist/flickity.pkgd.min.js"></script>