How to fade changing background image How to fade changing background image jquery jquery

How to fade changing background image


This is probably what you wanted:

$('#elem').fadeTo('slow', 0.3, function(){    $(this).css('background-image', 'url(' + $img + ')');}).fadeTo('slow', 1);

With a 1 second delay:

$('#elem').fadeTo('slow', 0.3, function(){    $(this).css('background-image', 'url(' + $img + ')');}).delay(1000).fadeTo('slow', 1);


Can I offer an alternative solution?

I had this same issue, and fade didn't work because it faded the entire element, not just the background. In my case the element was body, so I only wanted to fade the background.

An elegant way to tackle this is to class the element and use CSS3 transition for the background.

transition: background 0.5s linear;

When you change the background, either with toggleClass or with your code, $("#large-img").css('background-image', 'url('+$img+')'); it will fade as defined by the class.


This was the only reasonable thing I found to fade a background image.

<div id="foo">  <!-- some content here --></div>

Your CSS; now enhanced with CSS3 transition.

#foo {  background-image: url(a.jpg);  transition: background 1s linear;}

Now swap out the background

document.getElementById("foo").style.backgroundImage = "url(b.jpg)";

VoilĂ , it fades!


Obvious disclaimer: if your browser doesn't support the CSS3 transition property, this won't work. In which case, the image will change without a transition. Given <1% of your users' browser don't support CSS3, that's probably fine. Don't kid yourself, it's fine.