Useful Resources for Web Designers and Developers

Advertise

here through BuySellAds

How to Create Your Own jQuery Content Slider without a plugin

August 15, 2010 on Tutorials

This tutorial will show you how to create your own jQuery content slider. You may ask “Why create my own if there are hundreds of already made sliders out there?” This is true: I myself almost always use ready made plugins for my projects. Yet, it is always a good thing to know how they work. It also comes in handy – if you should ever want to customize it (it’s always harder to edit someone else’s code).

View in Github

So are you ready to get started? For more useful web tutorials you can visit our Tutorials page. On a side note, if you want to learn more advanced stuff, here is a great resource for jQuery from Udemy. Okay, now let’s begin:

Step 1: Create the Base Mark Up

What we need is a series of images in an unordered list:

1
2
3
4
5
6
7
<ul>
<li><img src="image1.jpg" /></li>
<li><img src="image2.jpg" /></li>
<li><img src="image3.jpg" /></li>
<li><img src="image4.jpg" /></li>
<li><img src="image6.jpg" /></li>
</ul>

Pretty straightforward code – view it in the browser and see a bunch of images listed from top to bottom.

Step 2: Add jQuery Code to hide unfocused images:

What we’re trying to achieve is to only show the first image of the list and hide the rest. We do this by applying some CSS rules via jQuery to the mark up we’ve created. We also want to line up the hidden images to the right – so we can add controls that animate the entire ul a little bit to the left at a time (see illustration below):

screenshot1 How to Create Your Own jQuery Content Slider without a plugin

Add the following code right above the closing head tag:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script>
$(window).load (function() {
	var theImage = $('ul li img');
	var theWidth = theImage.width()
	//wrap into mother div
	$('ul').wrap('<div id="mother" />');					
	//assign height width and overflow hidden to mother
	$('#mother').css({
		width: function() {
		return theWidth;
	  }, 
		height: function() {
		return theImage.height();
	  }, 
		position: 'relative',
		overflow: 'hidden'  	
	});
		//get total of image sizes and set as width for ul 
	var totalWidth = theImage.length * theWidth;
	$('ul').css({
		width: function(){
		return totalWidth;	
	}				
	});		
 
});//doc ready
 
</script>

In English: in the first script tag – we have connected to the jQuery library online. Then we go in the window.load() event *as supposed to document.ready() – because of an issue detecting image width and height with webkit browsers. Then we set up a couple of variables which are all the images inside the unordered list, along with their widths. We wrap the unordered list (using the .wrap() function) inside a div called “mother” with the CSS rules I mentioned.

Step 3: Add “Next” and “Previous” Buttons

In our HTML – add anchor tags with the class “next” (If you want to move forward the slider) and “previous” (to go backward) inside the list items:

1
2
3
4
5
6
7
<ul>
<li><img src="image1.jpg" /><a class="next" href="#">next</a></li>
<li><img src="image2.jpg" /><a class="next" href="#">next</a><a class="previous" href="#">prev</a></li>
<li><img src="image3.jpg" /><a class="next" href="#">next</a><a class="previous" href="#">prev</a></li>
<li><img src="image4.jpg" /><a class="next" href="#">next</a><a class="previous" href="#">prev</a></li>
<li><img src="image6.jpg" /><a class="previous" href="#">prev</a><a class="startover" href="#">startover</a></li>
</ul>

Note that you will not see these links when you preview the page. This is because they are tucked away outside the visible region of the overflow property we’ve created:

screenshot2 How to Create Your Own jQuery Content Slider without a plugin

Step 3: The Nifty .Animate()Method

Okay, now we’ve come to the part where we actually see some action. The whole point of what we’re trying to do is to move the list a little to the right – when the “next” link is clicked, and to the left if “previous” is clicked:

screenshot3 How to Create Your Own jQuery Content Slider without a plugin

Add the following javascript code inside the existing script tags:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$(theImage).each(		
function(intIndex){				
$(this).nextAll('a')
	.bind("click", function(){
		if($(this).is(".next"))	{
			$(this).parent('li').parent('ul').animate({
				"margin-left": (-(intIndex + 1) * theWidth)				
					}, 1000)	
			} else if($(this).is(".previous")){
			$(this).parent('li').parent('ul').animate({
				"margin-left": (-(intIndex - 1) * theWidth)				
			}, 1000)	
			} else if($(this).is(".startover")){
			$(this).parent('li').parent('ul').animate({
				"margin-left": (0)				
			}, 1000)
	}
	});//close .bind()									 
});//close .each()

Explanation: the code above starts out with the “.each” function – which is essentially a loop that looks for each of our images in the list. Then it finds all of the anchor tags next to the images (through .nextAll) and checks them for the assigned class. If the class says “next” – animate the parent (ul) to the left by applying a margin-left CSS property to it. The same thing goes for class “previous”. The only difference is the index is advanced vs. deducted multiplied by the image width. Lastly – is class “startover” which resets the slider to its original position.

Add the CSS code below inside the “head” tag so you can see the links and start testing them:

1
2
3
4
5
6
7
8
<style>
*{padding:0; margin:0;}
ul {}
ul li {float:left; list-style:none; position:relative; }
ul li a.next {position:absolute; left:100px;}
ul li a.previous{position:absolute; left:0px;}
ul li a.startover{position:absolute; left:200px;}
</style>

Step 4: Make ‘er Nice and Purrty

Technically – our slider is done. This section mainly focuses on making it look nice and presentable. So I grab this file: Slider Constructor from Graphic River. Slider Constructor is a high quality Photoshop filled with shiny slider buttons and controls that will surely bring life to your new slider. Create the buttons of your choice from this file and save them as individual .pngs.

screenshot4 How to Create Your Own jQuery Content Slider without a plugin

You can set a different button for each anchor tag in each slide. You can also place them anywhere you want with some CSS positioning. Either add an “id” attribute to the individual anchor tags, or an additional class (which is what I did). Below is the CSS for my demo – of course, you might want to code yours differently:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
*{
    padding:0; 
    margin:0;
}
ul li {
    float:left; 
    list-style:none; 
    position:relative;
}
ul li a{
    text-indent:-9999px; 
    outline:none;
}
ul li a.next {
    position:absolute; 
    left:100px;
}
ul li a.previous{
    position:absolute; 
    left:0px;
}
ul li a.startover{
    position:absolute; 
    left:200px;
}
/*styled*/
div#container{
    border:1px solid #666666; 
    -moz-border-radius:6px; 
    -webkit-border-radius:6px;  
    padding:13px; 
    clear:both; 
    overflow:hidden; 
    width:620px; 
    position:relative; 
    top:35px; 
    margin:0 auto; 
    background:#ebebeb; 
    -moz-box-shadow: 0px 45px 33px -32px #000; 
    -webkit-box-shadow: 0px 45px 33px -32px #000; 
    box-shadow: 0px 45px 33px -32px #000; 
    display:block;
}
ul li a.next.red{
    background:url(images/next-red.png); 
    width:57px; 
    height:73px; 
    position:absolute; 
    left:560px; 
    top:237px;
}
ul li a.next.green{
    background:url(images/next-green.png); 
    width:67px; 
    height:67px; 
    position:absolute; 
    top:286px; 
    left:486px; 
}
ul li a.previous.green{
    background:url(images/prev-green.png); 
    width:67px; 
    height:67px; 
    position:absolute; 
    top:286px; 
    left:105px;
}
ul li a.next.orange{
    background:url(images/next-orange.png); 
    width:239px; 
    height:62px; 
    position:absolute; 
    left:360px; 
    top:300px;
}
ul li a.previous.orange{
    background:url(images/prev-orange.png);
    width:239px; height:62px; 
    position:absolute; 
    left:20px; 
    top:300px;
}
ul li a.next.blue{
    background:url(images/next-blue.png); 
    width:57px;
    height:129px; 
    position:absolute; 
    top:150px; 
    left:562px;
}
ul li a.previous.blue{
    background:url(images/prev-blue.png); 
    width:58px; 
    height:129px; 
    position:absolute; 
    top:150px;
}
ul li a.previous.silver{
    background:url(images/previous-silver.png); 
    width:49px; 
    height:50px; 
    position:absolute; 
    top:305px; 
    left:360px;
}
ul li a.startover { 
    background:url(images/startover.png);
    width:176px; 
    height:73px;
    position:absolute; 
    top:280px; 
    left:420px;
}

Also – the good thing about this code is you can place and style the buttons individually.

Conclusion

There, there – you’ve just done yourself some good coding Sparky! Feel free to modify, re-factor and make the code better. This is as basic as it gets – so have fun tweaking it. Make sure you leave a comment or spread the word by retweeting or liking it in facebook. Don’t forget to check out this jQuery for beginners series from Udemy! Until next time!

  • Priya

    Thanks a lot. Trying to see how to avoid the sliding to the extreme left and make it look like a rotation of images. But This is really helpful for a starter like me. Thanks once again

  • Priya

    got it thanks

  • Anonymous

    why have you used intIndex in function and how are you getting this value.

    I have just start writing my own jquery and try to learn it deeply.

    Thanks

    • http://fearlessflyer.com Michael Soriano

      so intIndex is the number of image in the lineup. So if its the 1st image – its 1, the 2nd – its 2. We use that to multiply with the with – so we can grab the position (in pixels) to slide

  • Abel

    hi, i’d like to do an infinite loop in my slideshow, i think i can with appendTo to change the first element to the end so it will start again, but because of the slideshow layout (horizontal — float left) whenever i click the last next img so it will jump to the first img in the slideshow, because of it having to destroy the first element to append it after the last one (thus doing the loop) it shifts a bit because of the float left, and the slideshow doesn’t stop in the right place.

    overall this float left (for the imgs in the slideshow) it’s interfering. cause when it has to destroy the first img to put it after the last (for looping purposes) all the imgs get a shift to the left.

    can anyone tell me how can i make things stay in place while having to remove an element with float left?

  • Soof

    Very helpful tutorial!

    I have it fully functioning now, except I have my images coming in as a variable from Big Cartel so I can’t manually not include the “previous” button on the first image.. Therefore it slides to white space if you press previous on the first image, anything I can do?

    • http://fearlessflyer.com Michael Soriano

      I’m not so sure about remote images. do you have a url i can look at?

  • Sam Saarian

    Great job, thanks

  • writerdesigner

    I’ve spent hours upon hours on this, no syntax errors per DW CS6, but when I open my page to test in Chrome, the slide area appears as a black box. Nothing in it, no slides no previous or next errors. Does not work. I’ve also tried WowSlider and while it works outside my page, does not work when put inside the page. This is my 12th try at a slideshow, can’t understand why everyone else in the world can do it and I can’t make it work at all. Any advice? Thanks…

  • Merii

    Thanks a lot :D

  • vegancookbook

    I followed the tutorial but when I click the next button nothing happens.

  • mirko28

    Can i put my next and previous buttons outside of the slider ? I tried but it doesn’t work. What do i need to change to get it working?

  • Abhishek Chakraborty

    Is it possible to wrap this code in a setInterval function and auto slide it after set intervals with pauses of certain seconds in between. And once it reaches first slide it should stop sliding after that. Also, if this slide can auto play on page load.