Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery img src change not immediate

Tags:

jquery

image

src

I use jQuery in a simple image gallery. Images fadeOut, the src changes, and they fadeIn.

Frequently, the previous image is faded in; only once the element reaches full opacity is the new image displayed.

What could be causing the delay and subsequent jump to the new image?

HTML

<div id="slide">
    <img src="/img/products/image1.jpg">
</div>

JS

var index = 0;

$(function() {
    if (srcs.length > 1) {
        setInterval("slide(800, 800)", 6000);
    }
});

function slide(o,i) {
    index++;
    if (index == srcs.length) index = 0;
    $("#slide img").fadeOut(o, function() {
        $(this).attr("src", path + srcs[index] + ext);
        $(this).fadeIn(i);
    });
}

Edit: I put fadeIn() in fadeOut()'s callback, but now the problem occurs noticeably every time. The image fades out all the way, then fades all the way back in, then changes.

Solution: in this answer, the .each() function caused a slight flicker during the new image's fadeIn(), but removing the .each() portion entirely fixed this.

like image 516
Trojan Avatar asked Oct 27 '25 10:10

Trojan


1 Answers

I would recommend adding the fadeIn function as a callback function of fadeOut. That way you ensure the -out animation completes before the new image is loaded.

See documentation: http://api.jquery.com/fadeOut/

$('#slide img').fadeOut(o, function() {
    // Animation complete.
    // Do fadeIn function here
});
like image 70
brandonscript Avatar answered Oct 29 '25 08:10

brandonscript