Thursday, May 16, 2013

Change Background Image with a Fade Transistion Using CSS and jQuery

I came across a question recently regarding how to use a 'fade' effect when changing/rotate through various background images. The sites I've been working on lately seem to all utilize large background imagery and I have written several custom background rotation scripts to accomplish rotating homepage hero type effects with background images. The jQuery involved is something for another posts, but the CSS to achieve a fade effect is very simple.

You can fade a background image using CSS3 transitions. I have accounted for non-CSS3 browsers in jQuery implementations using more complex strategies, but for most applications this CSS3 strategy will do just fine. It will offer a nice fade on compatible browsers and just a plain transition on others.

Set up jQuery to change the background image, but apply the transition style using the below 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 */
}