Dimics

Learn everything you want to know. Graphic and web tutorials.

jQuery: Content slider

In this tutorial I will show how you can make a content slider with Javascript and jQuery. First we’re going to make the buttons, then make the basic HTML, style it with CSS, and finally animate it with jQuery.

Download Demo


Photoshop: 00:00
HTML: 06:00
CSS: 11:30
Javascript/jQuery: 20:00

You can make as much slides as you want since we’ve used variables to animate our slider. You can also change the width.

If you don’t want to dive into the code you can just include the javascript file into your html file and use the id and classes: #buttonPrev, #buttonNext, #slides, and .slide. Be sure to have the #slides positioned relative and the overflow of it’s parent to hidden.

Javascript/jQuery

I will give a short explanation of the javascript:
First we check if the document is ready with loading else it the javascript would slow down the loading time.

$(document).ready(function(){
});

Then we make our variables, we will get the number of slides, the width of one slide, make a variable to see on wich slide we are, and calculate the maximum we have to animate to:

var slides = $(".slide").length;
var slideWidth = $(".slide").outerWidth();
var currentSlide = 1;
var leftMax = slideWidth * -1 * slides + slideWidth;

Then we calclate and set the width of #slides so you can have more and less the 3 slides:

$("#slides").css({"width" : slides * slideWidth});

Then we make our fuctions that will animate the slider. We want to run them on a button click, we start with the previous button. When the button is clicked we”re going to check if the current slide is the first, if thats true we animate to te maximum (last slide). If the the current slide is not the first we wanna animate one back, so we will animate +800px since we animate negative. In both cases we want to update our currentSlide variable so we now on wich slide we are:

$("#buttonPrev").click(function(){
	if (currentSlide == 1)
	{
		$("#slides").animate({left : + leftMax + "px"}, 600);
		currentSlide = slides;
	}
	else
	{
		$("#slides").animate({left : "+=" + slideWidth + "px"}, 600);
		currentSlide = currentSlide - 1;
	};
});

For the next button we need to check if the current slide is the last one, in that case we want to animate to te first, to 0px. If the currentslide is not the last one we want to animate one forward so we substract 800px. And again in both cases update the currentSlide variable.

$("#buttonNext").click(function(){
	 if (currentSlide == slides)
 	{
		 $("#slides").animate({left : "0px"}, 600);
	 	currentSlide = 1;
	 }
	 else
	 {
		 $("#slides").animate({left : "-=" + slideWidth + "px"}, 600);
		 currentSlide = currentSlide + 1;
	 };
 });

I have commented the files, so download the source files and take a look at them.

Download Demo

I hope you like the tutorial, and if you have questions just post a comment.

Greetz,

Durgé