jQuery Slider Tutorial for beginners/dumbies….how I did mine

I have only been able to write javascript using the jQuery library for about 2 months now. I started with a great book: Javascript The Missing Manual by David Sawyer McFarland (published by Pogue Press/ O’Reilly). Highly recommend it. It starts with a crash course in basic javascript, and then goes on into using jQuery.

I am going to assume that you have at least a little knowledge of it, and you googled for jQuery slider tutorial, or you found a link to my blog through one of my posts at other popular design blogs. Why am I writing this? Good question, and I have a good answer. At least it is the answer I wanted when I searched for the same thing.

I really like jQuery because of the stuff it lets me do without relying on Flash (overused in my opinion, but that is a different topic for another day…maybe tomorrow!). One thing really freakin’ sucks about it though. If you did what I did, and googled for something like this, then you will understand. Every damn search came back with a list of plugins. Yes, yes, plugins are cool, and I agree there are a lot of good ones. But I am not a pro yet and I actually want to learn how to do this stuff myself. There are very few good tutorials out there, and the ones that are, are seriously over complicated. So I am going to show you how I built mine and explain on the way what is going on. Sorry for the long intro, but hopefully you are still with me and will read on!


Let me start off by saying, anything in the code blocks that has a # in front of it is referencing an element id. Anything with a period in front of it is referencing an element’s class. Got it? Good, lets get started.

Again, I am assuming you have a little knowledge of jQuery, or you probably wouldn’t be here. I am also going to assume that you know css pretty well, or you wouldn’t be getting into jQuery.

First, HTML wise you will need:

  • 1 div for the container that shows the content, positioned relative, and a width of what each slide will be. In my case it is 935px. With an id of slideContainer (using my id’s here so you can follow along), and overflow: hidden.
  • 1 div with in that with an id of slideWrap – this is the actual div that moves – and it needs to be the exact width of the number of slides you will have. In my case 4, so 935*4 = 3740px, positioned absolutely, left: 0, and top: 0
  • 4 divs withint the slideWrap, all with the class: slide – These are the individual slides that show the different content

Here is the actual HTML for it so far:

<div id="slideContainer">
    	<div id="slideWrap">
    		<div class="slide">Slide 1</div>
		<div class="slide">Slide 2</div>
		<div class="slide">Slide 3</div>
		<div class="slide">Slide 4</div>
	</div>
</div>

And the base css:

#slideContainer {
	position: relative;
	width: 935px;
	height: 260px;
	float: left;
	overflow: hidden;
	border: 1px #666666 solid;
}
 
#slideWrap {
	width: 3740px;
	height: 260px;
	position: absolute;
	top: 0;
	left: 0;
}
 
.slide {
	width: 935px;
	height: 260px;
	float: left;
}

Add some background colors so you know what the hell you are looking at.

Now lets start from the top of my js file.

$(document).ready(function($) {
		$('#controlLeft').hide();
 
		var currentPosition = 0;
		var slideWidth = 935;

Line one there says when the document is ready, do something. You will notice in my slider here that I have two ways of controlling it. A list (the cogs with numbers), or the arrows. Since I do NOT want you to go further left than the first slide, I immediately have to hide the left arrow, which you will notice is gone if you haven’t gone further in the slider. That is what line 2 does.

Hide the ‘a’ tag with an id of controlLeft. Pretty simple. Hide actually hides crap! When I first started into my jQuery adventures I thought, this is going to be a piece of cake. Ya….not so much.

The rest of the code in the chunk above is declaring variables:

  • currentPosition – this is how I determine what slide I am actually on
  • slideWidth – how long each slide in the slider is – in this case 935px

Here is the next block, but it doesn’t actually get used until later. This is the function that controls when to hide or show the arrows.

function controlMechanism () {
			if (currentPosition >= 3) {
			$('#controlRight').hide();
		} else {
			$('#controlRight').show();	
		}
 
		if (currentPosition <= 0) {
			$('#controlLeft').hide();
		} else {
			$('#controlLeft').show();	
		}	
		};

The first line gives the function a name, which is controlMechanism. All this is doing is checking the ‘currentPosition’ and determining what arrows to show. If currentPosition is greater or equal to 3, hide the right arrow(right arrow has an id of controlRight), otherwise show it. If currentPosition is less than or equal to 0, hide the left arrow (id of controlLeft), otherwise show it. That was the easy part. Now comes the harder stuff.

Next is the list that moves the slider (i have two options of moving mine).

$('#controlList li').click(function(evt) {
			evt.preventDefault()
			currentPosition = ($(this).index());
			$('#slideWrap').animate({'marginLeft' : slideWidth*(-currentPosition)});
 
			controlMechanism ();
		});

The first line is creating a click event on all the li’s within a div that has an id of controlList. You can ignore the evt.preventDefault, because originally I had ‘a’ tags within the li’s, and using them. The preventDefault was keeping the ‘a’ tags from doing what they normally do…which is linking to something.

The next line is setting currentPosition equal to the index of the li that was clicked. $(this) refers to the clicked li. The first line actually gets ALL of the list items. The index() is telling you what number in the array this returns.

What?? I know, right? Idiot explanation here: We have 4 slides. They get put into order as they are found. When you find the index of something, you start at 0, then count up. We have 4…start at zero and count up 4, you end up with 3. Even more dumbed down, index is 1 less than the number you have. 3rd li? Index of 2. First li? Index of 0. Got it?

So when you click one of those list items, it gets the index number of the li you clicked. After that, you have the actual animation.

Now it finds the div with an id of slideWrap, then attaches the animation effect to it. The actual movement is done by adjusting the left margin (which starts at 0). So, adjust the left margin by multiplying the slideWidth (935) by the negative of the currentPosition. Lets say you clicked on the second li, which has an index of 1. 935 *(-1) = -935px. Why do we want the negative? Cause we want the slider to actually move left. Take a piece of paper, hold it in front of you. The left side of it is at 0px. Now move it left. In css numbers you are going to make it -Xpx.

Last in that chunk you see this: controlMechanism. This is calling the function to see what arrows to show or hide. So it does the check each time you click on an li. Should I hide an arrow yet? I’ll go find out!

The last bit of javascript that actually involves the slider movement deals with the arrows themselves:

$('.controls').click(function(evt) {
			evt.preventDefault()
			currentPosition = ($(this).attr('id') == 'controlRight'
			? currentPosition+1 : currentPosition-1);
			$('#slideWrap').animate({'marginLeft' : slideWidth*(-currentPosition)});
 
			controlMechanism ();

Now we attach the click event to the actual arrows, which are really just styled ‘a’ tags. They BOTH have a class of ‘controls’, but each has a different id (controlLeft and controlRight). The first line gets any element with a class of ‘controls’. In this case, there are two (both arrows), then attach the click event. The second line we actually DO need this time. Without it, if you click on the arrow, it would jump up to the top of the page because it has a null link on it (#). But we want to prevent the ‘a’ tags from doing what they naturally do, therefore the evt.preventDefault. Just so you are aware, evt could have been anything. You could type in ‘pickle’…doesn’t matter.

The third and fourth line do a couple of things. We are going to set currentPosition again. The $(this) refers to the element you clicked on with a class of ‘controls’. We find the id attribute on the element, AND…if the id is ‘controlRight, add 1 to currentPosition, if it is not (which means its controlLeft), subtract 1.

The ? is like a mini if/else statement…if the id matches, do what is in front of the colon, otherwise do what is after the colon. Then we animate the slider again.

So lets say we are on slide 2, so currentPosition is already set then to 1. You then click on the left arrow (which does NOT match id’s). So currentPosition is then 1 less than what it is, in this example it goes back to 0. The animate then multiplies the slideWidth of 935 by -0, which is still 0. The left margin then goes back to 0, which means we are now at slide 1, and current position is set back to 0.

The last line AGAIN runs the controlMechanism function to check to see if it should hide any arrows. In the above example, it would hide the left arrow, because currentPosition is less than or = to 0.

And there you have it. That is the basic slider I made. The rest of the crud is content within the divs with a class of ‘slide’.

Conclusion

I know that was a lot for such a small bit of code, but I wanted to actually explain how to do it, and what each part was doing so that someone starting out in jQuery could understand it. jQuery is pretty damn awesome, but I have found that when you are trying to do something with it, it is best to sit back and plan out what you want to happen first. If you don’t, you end up with a big pile of crap that doesn’t do half what you expected. I start by laying it out on paper first, and once I have my action plan written down, THEN I start coding. Hope you actually learned something, and thanks for reading.

Tags: ,

5 Responses to “jQuery Slider Tutorial for beginners/dumbies….how I did mine”

  1. I applaud you for taking the time to go back to fundamentals and figure things out on your own. I’m doing the same thing with some string manipulation functions (like sentence case and proper case). It really makes you understand your language better, and it makes your logic stronger overall as well.

  2. jcDesigns says:

    Thank you sir! This kind of tutorial would have been extremely helpful when I was building it. The couple that I did find, didn’t go into depth as much of why they were writing what they did, and they were doing waaaaay more than needed.

  3. vaanipala says:

    Thanks a lot for such a great tutorial! As u had said, I could not find any good slider tutorial for beginner with good explanation. I had wasted a couple of days researching on sliders till i came to this tutorial. I only found 1000s of complicated slider plugins. Now this will give a head start to explore one of the main features of jquery -SLIDER. :)

  4. Naveen says:

    Thanks a ton……really helped me a lot.
    And you are right about sites showing lots of really complicated description. :-)

  5. Mark says:

    This is a great tutorial but the JS section gives me an error on the last line of the script. I copied and paste you’re javascript but it’s not working.

Leave a Reply