Sheldon
Sheldon

Reputation: 10095

How do I fade in the next image in the list using jQuery?

I have a list of images. I would like to fade in the next image after the previous image has faded out. I think it should be fairly simple..

<ul class="nav fading">
  <li><?= anchor("#","Supported by",array("class" => "footer-heading disabled")) ?></li>
  <li><?= img("assets/img/1.png") ?></li>
  <li><?= img("assets/img/2.png") ?></li>
</ul>

My code so far:

$(document).ready(function(){
    $(".fading img").hide(); //hide everything 
    $(".fading img:first").fadeIn(4000);
    $(".fading img:first").fadeOut(4000,function(){
        $(this).parent().next().fadeIn(4000);
    });
});

I've attempted to fade the same image in again, after it has been faded out and that works:

$(document).ready(function(){
        $(".fading img").hide(); //hide everything 
        $(".fading img:first").fadeIn(4000);
        $(".fading img:first").fadeOut(4000,function(){
            $(this).fadeIn(4000);
        });
    });

The problem arises when I try to fade in the next image in the list.

Upvotes: 0

Views: 71

Answers (2)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123533

To find an <img> from the other, you'll have to traverse back down a "generation" with .find() or .children(), having gone up with .parent():

$(this)             // the current, `:first` <img>
    .parent()       // to its parent <li> (2nd under the <ul>)
    .next()         // to the last <li>
    .find('img')    // to the <img> under the last <li>
    .fadeIn(4000);

Otherwise, the line was finding and attempting to .fadeIn() the <li> instead, which won't affect the <img> under it.

$(this).parent().next().fadeIn(4000);

Upvotes: 2

Kevin Lynch
Kevin Lynch

Reputation: 24723

I would suggest the following

Replace this

$(this).parent().next().fadeIn(4000);

With this

$(this).parent().next().find('img').fadeIn(4000);

Upvotes: 2

Related Questions