Search code examples
jqueryimagecallbackgalleryfade

How can I fade an image and replace it with another one?


I'm having trouble with my image gallery. For some reason the image fades out but the rest of the code doesn't execute, it just stops mid way. I've tried removing the fade out function and the code works fine, the images are swapped how they should be etc. What is it about the fade that I'm doing wrong?

 $('.frame').click(function() {
    $("#lightbox").toggleClass("fadeout", function (){
    var copy = $(this).children().clone();
    $('#lightbox').children().replaceWith(copy);
    $("#lightbox").toggleClass("fadeout");
    });
});

I'm a complete self-taught newbie so I might ask some daft questions.

    #lightbox {
    opacity: 1;
    padding: 0 0 0 1%;
    width: 89%;
    height: 100%;
    float: right;
    text-align: center;
    transition: opacity 1s ease;
}

#lightbox.fadeout {
    opacity: 0;
}

.frame {
    width: 100%;
    text-align: left;
}

<div id="gallery_container">
<div id="lightbox">
    <img src="images/IMG_6412.jpg" alt="">
    </div>
<div id="gallery_nav">
    <ul>
        <div class="frame"><img src="images/XA2.jpg" alt=""></div>
        <div class="frame"><img src="images/Mega002.jpg" alt=""></div>
        <div class="frame"><img src="images/IMG_6412.jpg" alt=""</div>
    </ul>
</div>
    </div>

Solution

  • You're not using the toggleClass function properly. The second parameter is a function, but according to the documentation, the second parameter must be a state indication which is a boolean value (True = show, False = hide)

    Based on your comments, here's something that should work:

    $('.frame').click(function() {
        var copy = $(this).children().clone();
        $("#lightbox").fadeOut(2000, function (){
          $('#lightbox').children().replaceWith(copy);
          $("#lightbox").fadeIn(2000);
        });
    });