Search code examples
jqueryimagefade

Breifly seeing old image after setting new src with jQuery


I want to

  1. Fade out the image
  2. Preload a replacement image
  3. Change the image source to display the new image
  4. Fade in the (new) image

For some reason, though when the image fades back in there is a very brief moment where the old image is seen then replaced by the new image. I don't think this is a timing conflict between image operations... what else would cause this flicker?

// old image: about.jpg
// new image: contact.jpg


$('#content').fadeTo(1500, 0.01, function(){
    var container = $(this);

    // gather image information
    var src = img.parent().attr('href');
    imgData = { 'alt': img.attr('alt'), 'src': src, 'cap': '' };

    // change background image & caption (after image has been cached)
    var imgSrc = sanitizeBackgroundImage( imgData );
    $.get( imgSrc, function(data) {

        // set background image src to preloaded image
        $("#content>img").attr({"src": imgData.src});
        $("#content>img").attr({"alt": imgData.alt});

        // update caption text
        $('#bottom-caption').html('<span>' + imgData.cap + '</span>');

        // fade image container back in
        console.log( 'before fadeIn: ' + $("#content>img").attr("src") );
        container.fadeTo(750, 1);                   
    });
});

The console correctly reads

before fadeIn: /images/large/contact.jpg

Solution

  • Can you try to start fade-in at image load? I think fade-in is started before the image is fully loaded and displayed.

    $("#content>img").load(function() { $('#content').fadeTo(750, 1); });
    
    $('#content').fadeTo(1500, 0.01, function(){ 
      var container = $(this); 
    
      // gather image information 
      var src = img.parent().attr('href'); 
      imgData = { 'alt': img.attr('alt'), 'src': src, 'cap': '' }; 
    
      // change background image & caption (after image has been cached) 
      var imgSrc = sanitizeBackgroundImage( imgData ); 
      $.get( imgSrc, function(data) { 
    
        // set background image src to preloaded image 
        $("#content>img").attr({"src": imgData.src}); 
        $("#content>img").attr({"alt": imgData.alt}); 
    
        // update caption text 
        $('#bottom-caption').html('<span>' + imgData.cap + '</span>');  
      }); 
    });