jQuery vertical slider

In this post I'm going to show you how to create a simple vertical slider with jQuery. To accomplish this task, we're going to use negative relative positioning on the top property of each element within our slider. This property will take each time the proper value for showing the affected element. We start with a basic markup like this:

<div id="slider">

	<img src="http://dev.css-zibaldone.com/onwebdev/post/star-rating/1.jpg" alt="" />
	<img src="http://dev.css-zibaldone.com/onwebdev/post/star-rating/2.jpg" alt="" />
	<img src="http://dev.css-zibaldone.com/onwebdev/post/star-rating/3.jpg" alt="" />


Now a couple of CSS styles in order to show just one image at time:

#slider {
	width: 400px;
	height: 300px;
	margin: 2em auto 0 auto;
	overflow: hidden;

#slider img {
	display: block;
	width: 100%;
	height: 100%;
	position: relative;

Finally, we create a progressive jQuery function with a timer and a self-incremented counter that we'll use together with the jQuery's eq() method:

$(document).ready(function() {

     var index = 0;

     window.setTimeout(function() {

     	index += 1;

     	if(index == 1) {

         	$('#slider img').eq(index).animate({
             	top: -300
         	}, 1000);


         if(index == 2) {

         	$('#slider img').eq(index).animate({
             top: -600
         	}, 1000);


     	window.setTimeout(arguments.callee, 2000);

    }, 1000);        


You can see the demo below.


Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Comments are closed.