Peachy
Peachy

Reputation: 653

Add caption from ALT or TITLE tag to jQuery slideshow

I am using a simple little jQuery script to rotate through some images. I'm wondering if there is a way to grab the alt or title tag from an image and have that text appear below the image in a p or div tag.

Here is what I have so far:

jquery:

$(function(){
    $('.fadein img:gt(0)').hide();
    setInterval(function(){
      $('.fadein :first-child').fadeOut(1000)
         .next('img').fadeIn(1000)
         .end().appendTo('.fadein');}, 
     3500);
});

CSS

.fadein { position:relative; height:350px; }
.fadein img { position:absolute; left:0; top:0; }

HTML

<div class="fadein">
<img src="1.jpg" alt="This is Image One" />
<img src="1.jpg" alt="This is Image two" />
</div>
<p>CAPTION GOES HERE</p>

Any tips for integrating a changing caption into this that is fed by the alt tag?

Thanks!

Upvotes: 0

Views: 1914

Answers (2)

David Thomas
David Thomas

Reputation: 253318

Here's one way to do it:

$(function() {
    $('.fadein img:gt(0)').hide();
    $('.fadein').next().text($('img:first').get(0).alt);
    setInterval(function() {
        $('.fadein :first-child').fadeOut(1000, function() {
            $(this).closest('div').next().text('');
        }).next('img').fadeIn(1000, function() {
            $(this).closest('div').next().text(this.alt);
        }).end().appendTo('.fadein');
    }, 3500);
});​

JS Fiddle demo.

Edited the answer to change the above to use caching of selectors, to minimise querying of the DOM:

$(function() {
    var fadein = $('.fadein');
    fadein.find('img:gt(0)').hide();
    fadein.next().text(function() {
        return fadein.find('img:first').attr('alt');
    });
    setInterval(function() {
        fadein.find(':first-child').fadeOut(1000, function() {
            fadein.next().text('');
        }).next('img').fadeIn(1000, function() {
            fadein.next().text(this.alt);
        }).end().appendTo(fadein);
    }, 3500);
});​

JS Fiddle demo.

Upvotes: 1

Zoltan Toth
Zoltan Toth

Reputation: 47667

Maybe something like this - DEMO

$(function(){
    $('.fadein img:gt(0)').hide();
    $('p').text( $("img:visible").prop("alt") );

    setInterval(function() {
      $('.fadein :first-child').fadeOut(1000)
         .next('img').fadeIn(1000)
         .end().appendTo('.fadein').end();
      $('p').text( $("img:visible").prop("alt") );
    }, 3500);
});

Upvotes: 1

Related Questions