Fade background image in and out with jQuery?

33,877

Solution 1

You can fade background colors but not background images. The way to work around this is to have your images as <img> tags and hide them by default display:none;. Give your images position:absolute and z-index:-1 so they act like backgrounds and are behind everything else.

Here's a quick example of images fading one after the other.

HTML

<img src=".." />
<img src=".." />

CSS

img{
 position:absolute;
 z-index:-1;
 display:none;
}

jQuery

function test() {
    $("img").each(function(index) {
        $(this).hide();
        $(this).delay(3000* index).fadeIn(3000).fadeOut();
    });
}
test();

Check working example at http://jsfiddle.net/RyGKV/

Solution 2

You can fade backgound-images! in and out!

jQuery:

$('#yourdiv').animate({opacity: 0}, 0).css("background-image", "url(image.jpeg)").animate({opacity: 1}, 2500);

Edit:

This will fade the whole div not onley the background-image.

Solution 3

Although you can't directly fade-in a background-image. You can fade-in a solitary element containing only a background-image...

Here's an example

Share:
33,877
Ryan Lester
Author by

Ryan Lester

Phone: +1(337) 935 0016 Email: [email protected]

Updated on February 11, 2020

Comments

  • Ryan Lester
    Ryan Lester about 4 years

    So far, I've tried a bunch of things to the effect of the following, without success:

    <script type="text/javascript">
    var x = 0;
    
    while (true) {
        /* change background-image of #slide using some variation
        of animate or fadeIn/fadeOut with or without setTimeout */
        x++;
    }
    </script>
    

    Any ideas?

  • Ryan Lester
    Ryan Lester about 13 years
    Awesome, thanks! Any idea how I can make this loop infinitely?
  • Ryan Lester
    Ryan Lester about 13 years
    Thanks so much, that's amazing!
  • Cantrelby
    Cantrelby over 11 years
    And you may need to preload the images first.
  • Sjoerd
    Sjoerd over 8 years
    This fades the whole div, not only the background image.