[jQuery] change background-image using a transition/fade

I’m trying to change the background image of a button. Using the css() function changes the background instantly. Is there a way to do a crossfade effect?

Here’s what I’ve got, but the fade effect doesn’t work:

var img_button_pos = 'images/forms/buttonbg_green.gif';
var img_button_neg = 'images/forms/buttonbg_red.gif';
var img_button = 'images/forms/buttonbg.gif';


			$(this).animate({backgroundImage: 'url("'+img_button_pos+'")'}, 500);
			$(this).css('background-image', 'url("'+img_button+'")');

<button type="submit" class="type_pos">Click Me</button>


background-image isn’t numeric, so it won’t work.

I think you will have to have IMG elements for the images, then you can crossfade them using fadeIn and fadeOut.

Somehow, I don’t think an IMG element will work well inside of a button element as a background.

Guess I’ll have to skip this one if that’s the only way.

Or have two buttons, absolutely positioned on top of each other.

You could fade the original background to about 5% or some low amount and then change the background source to the new image already set to the say 5% opacity then fade it in to 100%.

No, you can’t fade backgrounds because you can’t change the opacity of a CSS background image. You can only affect the opacity of entire DOM elements.

Using two buttons–that means you might run into the issue of having two buttons with the same name attribute.

Not really, one of them can just not have a name attribute at all. You can generate the extra button with JavaScript, and remove one button after the crossfading is done.

What if it’s clicked during the crossfade?

[edit]: ah, nevermind. Only the element that appears as the result of the crossfade would be clicked.

Then again, what would you specify if javascript were disabled?

If javascript is disabled, you just have one button with no fancy effects (or just one image). If JavaScript is enabled, it creates the second button, adds the second image and adds the event listeners for the crossfade effect.

Progressive enhancement!