Animate background image change with jQuery

Jonathan Lyon picture Jonathan Lyon · Jun 6, 2010 · Viewed 120.6k times · Source

I finally have this working now but would like to know how I can use JQuery's animate function to make the background image changes fade in nicely when you hover over the list items on the homepage:-

http://www.thebalancedbody.ca/

The Code to make this happen so far is:-

$("ul#frontpage li#277 a").hover(
    function() {
        $('#homepage_container').css('background-image', 'url(http://www.thebalancedbody.ca/wp-content/themes/balancedbody_V1/images/nutrition_background.jpg)');
    },
    function() {
        $('#homepage_container').css('background-image', 'url(http://www.thebalancedbody.ca/wp-content/themes/balancedbody_V1/images/default_background.jpg)');
    }
);

$("ul#frontpage li#297 a").hover(
    function() {
        $('#homepage_container').css('background-image', 'url(http://www.thebalancedbody.ca/wp-content/themes/balancedbody_V1/images/vibration_training.jpg)');
    },
    function() {
        $('#homepage_container').css('background-image', 'url(http://www.thebalancedbody.ca/wp-content/themes/balancedbody_V1/images/default_background.jpg)');
    }
);

etc etc

How would I add the ANIMATE function to this please - thanks!!!

Thanks

Jonathan

Answer

Pekka picture Pekka · Jun 6, 2010

I don't think this can be done using jQuery's animate function because the background image does not have the necessary CSS properties to do such fading. jQuery can only utilize what the browser makes possible. (jQuery experts, correct me if I'm wrong of course.)

I guess you would have to work around this by not using genuine background-images, but div elements containing the image, positioned using position: absolute (or fixed) and z-index for stacking. You would then animate those divs.