Reputation: 152707
I'm using banner images in background of body {background: url(banner1.jpg)}
I have multiple image like banner1.jpg, banner2.jpg, banner3.jpg.
I want to change images automatically after specific interval like 5-10 seconds.
How to do this with jQuery? I don't want to use inline images.
Upvotes: 2
Views: 20253
Reputation: 1
I would like to say that this information is very useful and it works. I tried something different using JQuery:
HTML:
<div id="pic"></div>
<div id="bat"></div>
CSS:
#pic {
position: absolute;
z-index: -98;
top: 0;
left: 0;
background-image: url ('http://wallpaperfast.com/wp-content/uploads/2013/05/Calm-sea-breeze-notebook-background-images-Desktop-Wallpaper.jpg');
display: none;
}
#bat {
position: absolute;
z-index: -98;
top: 0;
left: 0;
background-image: url('http://www.designmyprofile.com/images/graphics/backgrounds/background0172.jpg');
display: none;
}
JS:
$('#pic').css({
height: $(window).height(),
width: $(window).width()
}).fadeIn('slow', function () {
$('#pic').css('background-image', 'url(http://wallpaperfast.com/wp-content/uploads/2013/05/Calm-sea-breeze-notebook-background-images-Desktop-Wallpaper.jpg)');
$('#pic').fadeOut('slow');
$('#pic').fadeIn('slow');
});
Upvotes: 0
Reputation: 160863
var images = ['banner1.jpg', 'banner2.jpg', 'banner3.jpg'];
var i = 0;
setInterval(function(){
$('body').css('background-image', function() {
if (i >= images.length) {
i=0;
}
return 'url(' + images[i++] + ')';
});
}, 5000);
UPDATE: If you want to change image smoothly, I suggest put all banner images into one image, and set it as body's background image, then use .animate method with background-position to change the banner image.
Upvotes: 3
Reputation: 7847
Just set the background-image
of the element:
$(elem).css('background-image', 'url(banner2.jpg)');
EDIT to fade in and out, you'll need to fade the container element:
$(elem).fadeOut('fast', function() {
$(elem).css('background-image', 'url(banner2.jpg)')
.fadeIn('fast');
});
Upvotes: 3