Jquery does not return second image in list

1

Apparently, the code is correct, it is the following:

{
if( $(".ativo").next().size() ) 
{ 
    $(".ativo").fadeOut().removeClass("ativo").next().fadeIn().addClass("ativo")
}
else 
{ 
    $(".ativo").fadeOut().removeClass("ativo");
    $("#slide img").eq(0).fadeIn().addClass("ativo")
 }

And the current html:

<div id="slide">

            <a href="CURSOS.html"><img id="slideIMG1" src="IMAGENS/mao (370px) - Final.jpg" width="1155" height="370" alt=""/></a>
            <a href="#"><img id="slideIMG2" src="IMAGENS/picjumbo (370px).jpg" width="1155" height="370" alt=""/></a>

         </div>     
    
asked by anonymous 16.09.2015 / 14:15

1 answer

3

Your problem is that the image has no siblings, it is the only child of the link ( a ), so next will not return anything. To select the next image, it is necessary to go up to the parent, get the next link and then descend again to the image:

function mudar() { 
            
    if( $(".ativo").parent().next().size() ) 
    { 
        $(".ativo").fadeOut().removeClass("ativo")
            .parent().next().children("img")
            .fadeIn().addClass("ativo")
    }
    else 
    { 
        $(".ativo").fadeOut().removeClass("ativo");
        $("#slide img").eq(0).fadeIn().addClass("ativo")
    }
}
mudar();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><buttononclick="mudar()">Teste</button>
<div id="slide">

    <a href="CURSOS.html"><img id="slideIMG1" src="http://sempreupdate.org/wp-content/uploads/2014/12/google-small.png"alt="A"/></a>
    <a href="#"><img id="slideIMG2" src="https://s1.yimg.com/rz/d/yahoo_en-US_f_p_bestfit_2x.png"alt="B" class="ativo"/></a>

</div>

Alternatively, you can apply the class to a instead of img , simplifying your code (if you can do this without "breaking" your CSS too, of course).

    
16.09.2015 / 14:30