Nov 2, 2009

How to make very simple JavaScript slideshow with JQuery

I’ll continue my article about JQuery Effects - with this one. It would be short information on how to make custom JQuery slideshow animation.

Let’s start with a div containing our images. Here is the code:

<div id="slideshow">
    <img src="img1.jpg" />
    <img src="img2.jpg" />
    <img src="img3.jpg" />
    <img src="img4.jpg" />
    <img src="img5.jpg" />
    <img src="img6.jpg" />
</div>

I’m not really good at using CSS so it would be pretty simple.

#slideshow {
    position:relative;
    height:200px;
    width: 210px;
}
#slideshow img {
    position:absolute;
    top:10px;
    left:5px;
}

I’ll use some initializing code to hide all the images, and then I’ll show only the first one. Here is the code packed in a function.

function init() {
 $('#slideshow img').hide();

 $('#slideshow img:first').show();
}

And now, we must write the logic of our slideshow. We need to obtain the visible image, hide it and show the next one. When we hit the end, we need to revert back at the first element.
So let’s start with obtaining the visible image. It is simple with JQuery selectors:

var $top = $('#slideshow img:visible');

And get the next image:

$next = $top.next();

This won’t help us when we reach the last image. I’ll make a check for the last element:

var $next;
 if($top.next().length > 0)
  $next = $top.next();

 else
         $next = $('#slideshow img:first');

And now the action:

$top.hide();
$next.show();

Our slide function must be called on a regular basis. We will obtain this with the JS function setInterval.

setInterval( "slide()", 3000 );

And here is the full code:

<html>
<head>
<title>JQuery Slideshow examples</title>
<style>

#slideshow {
    position:relative;
    height:200px;
 width: 210px;
}
#slideshow img {
    position:absolute;
    top:10px;
    left:5px;
}
</style>
<script  src="jquery.js"></script>
<script>
function init() {
 $('#slideshow img').hide();

 $('#slideshow img:first').show();
}
function slide() {
    var $top = $('#slideshow img:visible');

    var $next;
 if($top.next().length > 0)
  $next = $top.next();

 else
        $next = $('#slideshow img:first');

 $top.hide();

 $next.show();
}

$(document).ready(function() {
 init();
    setInterval( "slide()", 3000 );
});

</script>
</head>
<body>
<div id="slideshow">
    <img src="img1.jpg" />

    <img src="img2.jpg" />
    <img src="img3.jpg" />
 <img src="img4.jpg" />

 <img src="img5.jpg" />
 <img src="img6.jpg" />
</div>
</body>
</html>

Working demo

2 comments:

Anonymous said...

Thanks a bunch! Very simple, very helpful.

vijibala said...

Thank you very much. This code is very easy to understand. Great!

Popular Posts