Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change background-image of a div with fade effect every 10 seconds with jquery

I would like to create a slideshow in the header area of my page. It should change the background image every 10 seconds with a nice fade effect. And since I'm using jQuery for other stuff already I would like to use it for that as well.

So my markup is just:

<div id="header">
    <!--other stuff here...-->
</div>

And my CSS at the moment is:

#header {
    background:  url('images/header_slides/slide_1.jpg') no-repeat;
}

So now what I want is that after 10 seconds it would change to

#header {
    background:  url('images/header_slides/slide_2.jpg') no-repeat;
}

with a nice slow fade effect.

like image 652
Gogogo Avatar asked Mar 31 '11 23:03

Gogogo


2 Answers

I answered a similar question at How to fill browser window with rotating background Image?. You can fade background colors but not background images. You must have your images in <img> tags and hide them by default display:none;. Give your images position:absolute and z-index:-1 so your images acts like a background images and are behind everything else.

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

Check working example at http://jsfiddle.net/ewsQ7/5/

like image 184
Hussein Avatar answered Nov 07 '22 09:11

Hussein


You can fade a background image with CSS3 using transitions.

Check it out at https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_transitions

For your use, set up jQuery to change the background image, but apply the transition style using CSS. Anytime the background changes, it will transition according to the CSS3 style.

#header
{
    background: url('images/header_slides/slide_1.jpg') no-repeat;
    transition: background 0.5s linear;
    -moz-transition: background 0.5s linear; /* Firefox 4 */
    -webkit-transition: background 0.5s linear; /* Safari and Chrome */
    -o-transition: background 0.5s linear; /* Opera */
}
like image 37
Robert Waddell Avatar answered Nov 07 '22 10:11

Robert Waddell