Trojan
Trojan

Reputation: 2254

jQuery img src change not immediate

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.

Upvotes: 4

Views: 2405

Answers (3)

Javis Perez
Javis Perez

Reputation: 4350

You can try something like this on your preload function:

$.each(imgArray, function() {
    var i = new Image();
    i.src = path + this + ext;
});

Instead of ajax call, and also try this on your slide function:

$('#slide img').fadeOut(o, function(){
    var that = this;
    this.src = path + srcs[index] + ext;
    this.onload = function() {
        $(that).fadeIn(i);
    };
});

Upvotes: 1

brandonscript
brandonscript

Reputation: 72885

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
});

Upvotes: 1

sareed
sareed

Reputation: 780

It is because javascript does not wait for the fadeOut to complete before continuing through the code use something like this

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

and it should wait until the fadeOut is completed before starting the fadeIn.

Upvotes: 1

Related Questions