Search code examples
javascriptjquerycssbackground-imagefadein

jQuery fadeOut and fadeIn background-image


When I click a certain link I want the background-image to fadeOut, change to another image and then fadeIn.

The code I have:

$('.link').on('click',function(){
    var image = $(this).data('image');
    $('#div-with-the-bgimage').css('background-image', 'url('+image+')');
})

I tried this:

$('.link').on('click',function(){
    var image = $(this).data('image');
    $('#div-with-the-bgimage').fadeOut('3000').fadeIn('3000').css('background-image', 'url(' + image + ')');
})

but this didn't work, what am I doing wrong? (I'm new to jQuery)

EDIT:

I solved this with Rory McCrossan answer:

$('.link').on('click',function(){
    var image = $(this).data('image');
    $('#div-with-the-bgimage').fadeOut('3000', function() {
        $(this).css('background-image', 'url('+image+')').fadeIn('3000');
    });
});

But now this fadesOut to a white background and and then fadesIn to the image, giving a sensation of a flash? Is there a way to load the image before?


Solution

  • You need to chain the fades by calling the fadeIn after the fadeOut has completed. You can do this by using the callback function parameter. Try this:

    $('.link').on('click',function(){
        var image = $(this).data('image');
        $('#div-with-the-bgimage').fadeOut('3000', function() {
            $(this).css('background-image', 'url('+image+')').fadeIn('3000');
        });
    });