I am unable to get the image alt tag with javascript. Is it possible and how?
Maby something like: $caption.text( flkty.selectedElement ).attr('alt') (last javascript line)
But I do not get it working ...
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 {
/* display: block; */
/* max-height: 100%; */
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>
Use attr
const img = document.getElementById('image')
const alt = img.getAttribute('alt')
console.log(alt)
<img id="image" src="https://picsum.photos/200/300" alt="this it the alt attribute" />
With jQuery:
const alt = jQuery("#image").attr('alt')
console.log(alt)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img id="image" src="https://picsum.photos/200/300" alt="this it the alt attribute" />
There's a small error in your code:
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).find('img').attr('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>