Monday, March 12, 2012

Background Image Change on every 5sec using Jquery

In this article, will show you how to change background image on some period of time . So here is the tutorial to apply this kind of effect to your web project. You can achieve it in few lines of jquery. Use it and make  your website more beautiful.


CSS Code

<style type=”text/css”>
div.background {
position:absolute;
left:0px;
top:0px;
z-index:-1;
}
div.background img {
position:fixed;
list-style: none;
left:0px;
top:0px;
}
div.background ul li.show {
z-index:500
}
div.background {    position:absolute;    left:0px;    top:0px;    z-index:-1;}div.background img {    position:fixed;    list-style: none;    left:0px;    top:0px;}div.background ul li.show {    z-index:500}
</style>

Javascript Code

Below is the jquery code used to change background image.In this i have set for 5sec. To change sec you have to change setInterval(‘change()’,5000);

<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js”></script>
<script type=”text/javascript”>
function thebackground() {
$(‘div.background img’).css({opacity: 0.0});
$(‘div.background img:first’).css({opacity: 1.0});
setInterval(‘change()’,5000);
}
function change() {
var current = ($(‘div.background img.show’)? $(‘div.background img.show’) : $(‘div.background img:first’));
if ( current.length == 0 ) current = $(‘div.background img:first’);
var next = ((current.next().length) ? ((current.next().hasClass(‘show’)) ? $(‘div.background img:first’) :current.next()) : $(‘div.background img:first’));
next.css({opacity: 0.0})
.addClass(‘show’)
.animate({opacity: 1.0}, 1000);
current.animate({opacity: 0.0}, 1000)
.removeClass(‘show’);
};
$(document).ready(function() {
thebackground();
$(‘div.background’).fadeIn(1000); // works for all the browsers other than IE
$(‘div.background img’).fadeIn(1000); // IE tweak
});
</script>

HTMl COde

Below is the html code here you can see that all  images are inside one  div with the class name of  background.Here i have used three  images, you can add images  as much you want.

<div class=”background”><img src=”millenniumBridge.jpg” width=”1400″ height=”819″ alt=”pic1″ /><img src=”bg_trinity.jpg” width=”1401″ height=”934″ alt=”pic2″ /><img src=”bg_clare_college.jpg” width=”1400″ height=”934″ alt=”pic3″ /></div>

No comments:

Post a Comment