コードバ リノ コードバ リノ - 2 months ago 16
HTML Question

Changing Image Src after animation in Jquery

So I am making a polaroid slideshow effect and I want to change the image after the animation in Jquery. I tried adding Delays but maybe I'm not doing it right?

Here's my code and maybe you can help find a way to add transitional images

Jquery


$(function () { // DOCUMENT ready shorthand
function polariodSlideshow() {
$("#polaroid").animate({ opacity: 1, top: 80 }, 1500);
$("#polaroid").animate({ opacity: 0, top: 250 }, 1800);
$("#polaroid").animate({ opacity: 0, top: 0 }, 1900, polariodSlideshow);
}
polariodSlideshow();
});



HTML

<div id="polaroid" style="position:absolute ;width: 100%; height: -3000px; margin-top: 35px; opacity:0.0">
&nbsp;&nbsp;&nbsp; <br /> <br />
<div style="background-color: #EEEEEE; height:145%; width:40%; box-shadow: 0px 10px 5px #888888; display:inline-block; margin-left: 15%;">

<div id="slideshow">
<img id="centerIMG" src="images/cityscape.jpg" style=" margin-top:15px; width: 94%; margin-left:3%;" />

</div>

<div style=""> <br /> <br /> </div>
</div>
</div>


I'm looking to add the switch after the third animation, so the callback function would happen after the image is changed when the animation is done.

Answer

You just use the completion handler from the third animation:

$(function () { // DOCUMENT ready shorthand
    var imgs = ["src1.jpg", "src2.jpg", "src3.jpg", "src4.jpg"];
    var cntr = 0;
    function polariodSlideshow() {
        $("#polaroid").animate({ opacity: 1, top: 80 }, 1500);
        $("#polaroid").animate({ opacity: 0, top: 250 }, 1800);
        $("#polaroid").animate({ opacity: 0, top: 0 }, 1900, function() {
            // change the image here
            var newImg = imgs[cntr % imgs.length];
            ++cntr;
            // use newImg here

            // then kick off the next iteration
            polariodSlideshow();
        });
    }
    polariodSlideshow();
});

If the new image .src is not already cached, then you may also need to add code that waits for it to load or better yet, make sure it's precached so that isn't an issue.

Comments