Animate Full-Page Multiple Background images with fade-in & fade-out effect – jQuery

“How to change multiple background-image of body with effects?” – I think this is a major problem which all designers face. 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 multiple images fading one after the other.

jquery-full-page-animated-background-images

The HTML

Html is very simple. Just add a div with multiple images which you want to animate / change in background with fade effects.

<div id="wrap">
<img class="bgfade" src="http://farm9.staticflickr.com/8526/8668341950_182b74faf2_z.jpg">
<img class="bgfade" src="http://farm9.staticflickr.com/8532/8667337535_6da0a9a261_z.jpg">
<img class="bgfade" src="http://farm9.staticflickr.com/8540/8667244539_d227f8c435_z.jpg">
</div>

The CSS

Now, We will use some CSS Technique which will create an illusion like background-image animation. 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. Now, set css property of div#wrap which includes these images to “position:fixed” and “top:0; left:0;” so that it will fix with page background.

#wrap{
	position:fixed;; 
	z-index:-1; 
	top:0; 
	left:0; 
	background-color:black
}
#wrap img.bgfade{
	position:absolute;
	top:0;
	display:none;
	width:100%;
	height:100%;
	z-index:-1
}

jQuery

Now, it is java-script’s turn. We will calculate browser window’s height & width. After that we will set width/height of div#wrap to browser so that background cover entire webpage. Now we have to animate our images. We will simple use function of fadeIn() and fadeOut() in images for this.

$(window).load(function(){
$('img.bgfade').hide();
var dg_H = $(window).height();
var dg_W = $(window).width();
$('#wrap').css({'height':dg_H,'width':dg_W});
function anim() {
    $("#wrap img.bgfade").first().appendTo('#wrap').fadeOut(1500);
    $("#wrap img").first().fadeIn(1500);
    setTimeout(anim, 3000);
}
anim();})
$(window).resize(function(){window.location.href=window.location.href})

Updated

I have updated the script. Actually, after re-sizing the browser we have to update the width/height of div#wrap. So, I am going to reload this window, when ever browser will re-size. It will help to re-calculate all these and refresh the animation. Div#wrap will re-size according to browser window and play animation smoothly.

view demo

You may like:

Posted by: Dhiraj kumar