Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fade one image into another

This should be a simple question. When I press a button, I'd like to fade out one image and fade in a new one. I have a button binded to this function:

function changeBackground() {
var background = document.getElementById("background");
var h_background = document.getElementById("background_hidden")

$('#background').fadeOut('slow', function() {$('#background_hidden').fadeIn('slow')});
}

In the CSS, h_background has a display: none; attribute. With this function as it is, the current image will fade out and the other one will display but it does not fade in - it shows up suddenly.

Any ideas of what I might be doing wrong?

Added a jsfiddle, but it currently does not work - trying to figure out why. http://jsfiddle.net/qrCjA/8/

like image 382
joshft91 Avatar asked Nov 04 '22 11:11

joshft91


1 Answers

I forked your fiddle and cleaned the code a little: http://jsfiddle.net/4FzqA/.

After looking between my cleaned version and your original, the only difference was that the fiddle was set to "onDomReady" on mine, when yours is set to "onLoad".

Otherwise, the code should have been functional.

window.onload = function() {
    var button = $("#fade_out").click(changeBackground);
}

function changeBackground() {
    $('#background').fadeOut('slow', function() {
        $('#background_hidden').fadeIn('slow');
    });
}

Edit: It looks like the window.onload was conflicting with the onLoad in the original fiddle, since the original fiddle didn't work for me. When I changed window.load to document ready, all was well, so:

$(document).ready(function() {
    var button = $("#fade_out").click(changeBackground);
});

Another edit: If the image is large, you could try waiting for it to load, but keep in mind that the load won't trigger if pulled from cache:

$(document).ready(function(){
   var img = new Image();
   $(img)
      .hide()
      .load(function(){
         $("body").append(this);
         $(this).fadeIn(3000);
      })
      .attr("src", "files/originals/01.jpg");
});

Taken from: Fading in large images in Chrome.

Another edit: From the sounds of it, you might be correct in guessing that it is an issue with the image size. I updated my original fiddle (http://jsfiddle.net/4FzqA/7/) with the new images and the load. Notice that the image is loaded each time which isn't very efficient. But it will give you an idea. Below is the JS:

$(document).ready(function() {
    var button = $("#fade_out").click(changeBackground);
});

function changeBackground() {
    $('#background').fadeOut('slow', function () {
        $('#background_hidden')
            .attr('src', 'http://img688.imageshack.us/img688/8633/daynightm.jpg?' + (new Date()).getTime())
            .load(function () { 
                $(this).fadeIn('slow'); 
            });  
    });
}
like image 111
dyersituations Avatar answered Nov 09 '22 07:11

dyersituations