Background slider

Below we have the code for a jQuery based background slider. No additional CSS or HTML modifications are required. The following slider creates DIV elements automatically and also resizes them to fit the window, together with preloading the necessary images.

/* BG Slider */ 
var $bg_slider = {
 	style: "position: fixed;z-index: -98;top: 0;left: 0;width:100%;height:100%;display: none;background-attachment:fixed;background-repeat:no-repeat;background-position:top center;-webkit-background-size:cover;-moz-background-size:cover;-o-background-size:cover;background-size:cover;",
 	list: new Array(),
 	url: '',
 	active: 'bg1',
 	inactive: 'bg2',
 	current: 0,
  	init: function(list)
 	{
 		$bg_slider.list = list,
 		$bg_slider.active = $("<div id='#" + $bg_slider.active + "' style='"+ $bg_slider.style +"'></div>"),
  		$bg_slider.inactive = $("<div id='#" + $bg_slider.inactive + "' style='"+ $bg_slider.style +"'></div>");
   		$('body').prepend($bg_slider.active);
 		$('body').prepend($bg_slider.inactive);
  		$bg_slider.preload();
 		$bg_slider.resize();
  		$( window ).resize(function() {
 			$bg_slider.resize();
 		});
 	},
  	resize: function()
 	{
 		$bg_slider.active.css({
 			height: $(document).height() - 1,
 			width: $(document).width()
 		});
  		$bg_slider.inactive.css({
 			height: $(document).height() - 1,
 			width: $(document).width()
 		});
 	},
  	preload: function ()
 	{
 		for (var a in $bg_slider.list) {
 			$('<img/>')[0].src = $bg_slider.list[a];
 		}
 	},
  	change: function()
 	{
 		var total = $bg_slider.list.length - 1,
 			next = $bg_slider.current + 1,
 			active = $bg_slider.active,
 			inactive = $bg_slider.inactive;
  		if (next > total) { next = 0; }
 		$bg_slider.current = next;
  		inactive.css('background-image', 'url("' + $bg_slider.list[next] + '")');
 		inactive.fadeIn('slow');
 		active.fadeOut('slow');
  		var sw = $bg_slider.active;
 		$bg_slider.active = $bg_slider.inactive;
 		$bg_slider.inactive = sw;
 	}
}Code language: PHP (php)

Using the script:

jQuery( document ).ready(function() {
 	$bg_slider.init(
 		Array(
 			"1.jpg",
  			"2.jpg",
  			"3.jpg",
  			"5.jpg"
 		)
 	);
  	setInterval(function(){
 		$bg_slider.change();
 	}, 10000);
});Code language: PHP (php)

The code above inits the background slider with a list of images and then uses javascript’s setInterval function to change the images every 10 seconds.