How to add a fadeIn effect while changing background image using .css in Jquery

1.9k views Asked by At

Hey guys, Im trying to add a fadein effect while changing my background image using .css in Jquery I dont really know much about java, hoping someone can help me out here!

The code for changing css background image is pretty simple here:

$(document).ready(function(){
$("#button01").click(function () {
      $("#content_wrapper").css({backgroundImage : 'url(image/staff/shinji.jpg)' } );
        });
    }); 

It's like a image gallery, Im just showing it in css background image everything works fine, but I was wondering if it's possible to add the fadeIn or fade-to effect.

2

There are 2 answers

1
Acorn On

You can't fade one image to another, only properties such as solid background colours.

What you can do is fade the opacity of an element containing an image.

Using this method, what you will have to do in order to achieve the effect you want is to have 2 images one on top of the other.

Then you can fade out one while fading in the other.

So something like:

// write a little function to do a toggling fade
jQuery.fn.fadeToggle = function(speed, easing, callback) { 
   return this.animate({opacity: 'toggle'}, speed, easing, callback); 
};

// make sure one layer is marked as active and shown and the other is hidden
$("#layer1").show();
$("#layer2").addClass('inactive').hide();

// then you can do this:
$("#button01").click(function () {
    $("#layer1").fadeToggle('slow').toggleClass('inactive');
    $("#layer2").fadeToggle('slow').toggleClass('inactive');
    // then set the new background image for the hidden layer
    $(".inactive").css({backgroundImage : 'url(image/staff/shinji.jpg)' } );
};

Probably not a beautiful way of going about it, but I think it should work.

5
Alex On

For the fade effect, you need to have both images visible to some degree at the same time. I suggest you use 2 layers. The bottom will always contain the image you want to fade out to. The layer on the top will contain the image which will become transparent.

You won't be able to have ANY content inside your container with the fading background, or the fade effect will also influence the contents.

Then using the jQuery with effects, do this:

$('#element').fadeOut('slow', function() {
    // Animation complete.
});