vtvmsa
Last Updated: February 25, 2016
·
21.16K
· zamith

Change the background image with animate

It is not possible to change the background image of a DOM element with animate (misleading title, sorry about that :P), so here is a pretty nice workaround that will get you that fade in/fade out effect you always wanted when changing images.

This works by first reducing the opacity of the current image to 0, making it invisible, and when this has finished apply the new style and making the opacity 1 again with a soft fade in effect. Nice. :D

$("#image").stop().animate({opacity: 0},1000,function(){
    $(this).css({'background-image': "url('/images/alt_image.png')"})
               .animate({opacity: 1},{duration:1000});
 });

Note: The stop function is there just to prevent the effects queue to grow to deep, i.e, if this is triggered by a click and the user clicks multiple times, only the last animation will actually run, all the others will be stopped.

3 Responses
Add your response

1972

Can you provide an example of this is in use somewhere?

over 1 year ago ·
1973

Sure.

Check the logo on the header of http://www.groupbuddies.com/. As you scroll down it changes with a nice animation.

over 1 year ago ·
13965

Hi, the example you showed is having one image url. if i have, say, 3 images which I want to animate in the background within a div then how should i put the image urls ?

over 1 year ago ·