How to Create a Simple iTunes-like Slider

How to Create a Simple iTunes-like Slider

Tutorial Details
  • Technology: jQuery
  • Difficulty: Intermediate
  • Estimated Completion Time: 30 Minutes

When space is at a premium, making use of sliders is the optimal way to present information. Today, we’ll take a look at how to create a slider similar to the one used in the iTunes store.

iTunes Version

Developers often seek the functionality provided by sliders in order to fit lots of information in the space provided. But creating such a slider is not as difficult as you might think. With a little planning and some experimenting, you can create one rather quickly.

I believe a demo is worth a thousand words. Hit the demo and try it out yourselves.

Interested? Let’s get started right away!

Design Goals

Before we start coding, here are a few goals for this widget.

  • Minimize the space taken up by images by making the slideshow’s dimensions the same size of a single image and then fading between them.
  • Provide a vertical carousel of images on the side showing upcoming images.
  • Provide a method to manually move the carousel and the slideshow forward. In this instance, we make use of a simple anchor element.
  • On the carousel, the top most image is the next in line and will be displayed when the next button is clicked.
  • Minimize DOM manipulation as much as possible. That’s not to say we aren’t going to touch the DOM, it’s just that we aren’t going to meddle with the DOM too much.

Plan of Action

There are actually a handful of techniques to make a widget like this. For our purposes today, I’m going to stick with a technique which adheres to a saying:

When in doubt, use brute force.

Step 1: Setup the CSS for the gallery container so that all the main images collapse into taking the space of a single image. I’ll explain this point later below.

Step 2: Setup the CSS for the thumbnail container so that only three images are visible at once.

Step 3: Cycle through the images and assign a class to each thumbnail and image with a numeric index to identify each independently. For example, each image gets a class of thumb-xx where xx is a number.

Step 4: When the next button is clicked, move the carousel one thumbnail up and then display the thumbnail’s corresponding image.

These are the basic steps involved in creating such an effect. I’ll explain each step in detail as we go along.

Step 1: Core Markup

The HTML markup for the demo page looks like so:

<!DOCTYPE html>  
<html lang="en-GB">  
	<head>
		<title>iTunes slider</title>
		<link rel="stylesheet" href="style.css" type="text/css" />
	</head>

	<body>
    	<div id="container">
        	<h1>Create a simple iTunes-esque slider with jQuery</h1>
		<div>by Siddharth for the lovely folks at Net Tuts</div>
		<p>A simple slider/slideshow which mostly emulates the one on iTunes barring a few changes. Click the down button to cycle the images.</p> 
        
		<div id="gallery">
    		   <img src="img/1.jpg" />
    		   <img src="img/2.jpg" />
    		   <img src="img/3.jpg" />
    		   <img src="img/4.jpg" />
            	   <img src="img/5.jpg" />
            	   <img src="img/6.jpg" />
	        </div>
        
                <div id="thumbs">
    	   	   <img src="img/11.jpg" />
    		   <img src="img/22.jpg" />
    		   <img src="img/33.jpg" />
    		   <img src="img/44.jpg" />
            	   <img src="img/55.jpg" />
            	   <img src="img/66.jpg" />    
	        </div>
        
        	<a href="#" id="next"></a>
        </div>
        
	<script type="text/javascript" src="js/jquery.js"></script>
	<script type="text/javascript" src="js/mocha.js"></script>

	</body>
</html>

Disregarding the boiler plate code, we have two container elements full of images: one for the main gallery images and one for the thumbnails. I’ve given an ID to both of them so they can be easily accessed from the JavaScript. We also include an anchor element which acts as the next button.

We include the jQuery library and our own script file at the end.

At the end of this stage, our demo page looks like just a list of images.

Tutorial Image

Step 2: CSS Styling

*{
	margin: 0;
	padding: 0;
	border: 0 none;
	outline: 0;
}

body{
	font-family: "Lucida Grande", "Verdana", sans-serif;
	font-size: 12px;
}

p{
	margin: 20px 0 40px 0;
}
h1{
	font-size: 30px;
	font-family: "Myriad Pro", "Lucida Grande", "Verdana", sans-serif;
	padding: 0;
	margin: 0;
}

h2{
	font-size: 20px;
}

#container{
	width: 900px;
	margin-left: auto;
	margin-right: auto;
	padding: 50px 0 0 0;
	position: relative;
}

img{
	display: block;
}

#gallery, #thumbs{
	float: left;
}

#gallery{
	width: 800px;
	height: 300px;
	overflow: hidden;
}

#gallery img{
	position: absolute;
}

#thumbs{
	width: 100px;
	height: 300px;
	overflow: hidden;
}

#next{
	display: block;
	width: 47px;
	height: 43px;
	background: url(img/arrow.png);
	position: relative;
	top: 257px;
	left: 855px;
}

#next:hover{
	background: url(img/arrowmo.png);
}

.clear{
	clear: both;
}

The CSS is pretty self explanatory but there are a couple of points I want you to take note of:

First up, notice that I’ve applied position: absolute to #gallery img. This makes sure that the images are stacked on top of each other instead of one below the other. This way we can later manipulate their opacity to decide which image to show.

Secondly, notice that the thumbs element has its height set to 300px. This is because the thumbnails in the demo are 100px tall each and I want the carousel to show 3 images at once. Essentially, for your own implementation, multiply the height of a thumbnail by the number of thumbnails you want to show at once to find the required height of the element.

Also, take note of the fact that we’ve set its overflow property to hidden to make sure no more than 3 thumbnails are shown at once.

After we’ve styled our slider, it looks like the image below. Notice that almost everything is in place. The last image is stacked at the top and is thus visible.

Tutorial Image

Step 3: JavaScript Implementation

Now that we have a solid framework and some basic styling in place, we can begin coding the required functionality. Note that we make extensive use of jQuery. Feel free to link to Google’s CDN if necessary.

Procuring the Elements and Prepping them

We first need to acquire the images and their corresponding thumbnails so that we can process them.

	var images = $("#gallery img");
	var thumbs = $("#thumbs img");
        var index = 0;

The above snippet will take care of obtaining the list of images and thumbnails, and storing them for later use. We also create a variable called index to denote which element to start from. For now, I’m setting it to start from the first element. Note that index is zero based.

	for (i=0; i<thumbs.length; i++)
	{
		$(thumbs[i]).addClass("thumb-"+i);
		$(images[i]).addClass("image-"+i);
	}

Next, we just iterate through both the lists and and add a class of thumb-xx or image-xx to each element where xx is a number. This lets us look for each individual thumbnail or image independently.

Hooking up the Handler

We now need to create an event handler and attach it to the next button so that we can do something when the button is clicked.

$("#next").click(sift);

The one liner above will take care of that. Essentially, we ask it to call the sift function everytime next is clicked.

function sift()
	{
		if (index<(thumbs.length-1)) {index+=1 ; }
		else {index=0}
		show (index);
	}

This is a very simple event handler actually. We just check to see what element is currently selected. If it is the last, we reset the index so the carousel goes back to the first element, thus creating a pseudo infinite carousel. Otherwise, we increment index by 1.

Next, we call the function show, passing in the index variable as a parameter. We’ll create the function in a bit.

Step 4: Implementing the Core Logic

function show(num)
	{
		images.fadeOut(400);
		$(".image-"+num).stop().fadeIn(400);
		var scrollPos = (num+1)*imgHeight;
		$("#thumbs").stop().animate({scrollTop: scrollPos}, 400);		
	}

The show function implements the core functionality of this widget. Let me explain each part.

First, we fade out every image the gallery element contains. Next, we fade in just the required image making use of its class. Since each image can be accessed through its class and we have access to the positional index of the image, we just use the following selector: “.image-”+num

Next, we need to scroll the thumbnail element so that the required image is at the top of the carousel. There are two ways to go on about doing this.

The first method makes use of jQuery’s position property. This lets us find the element’s position relative to its parent element. Unfortunately, I’ve been running into quite a few problems with it and Chrome which means we’ll have to use our second method.

The next method is actually just as simple. Since we can easily obtain the height of a thumbnail and since each thumbnail is required to be of the same height, we can easily just find the product of the nth element’s position in the list and the height of a thumbnail to obtain its offset from the top.

var imgHeight = thumbs.attr("height");

The above line lets us obtain a thumbnail’s height. Remember that a collection of elements can be queried just like a normal element.

var scrollPos = (num+1)*imgHeight;

We now calculate the offset of the thumbnail we need. Since we need the thumbnail of the next element in the list and not of that image itself, we increment it by 1 before multiplying it by the height.

With all this info, we can now scroll the element to the height we need.

$("#thumbs").stop().animate({scrollTop: scrollPos}, 400);

We use jQuery’s animate property to alter the scrollTop property to the value we calculated above. If you are new to jQuery’s animation functions, refer to my earlier article. Essentially, we scroll the element x pixels from the top to create a carousel effect.

Step 5: A Few Tweaks

Polishing the Pseudo Infinite Effect

We are essentially done but a few quick bits of code will make it a little bit more polished.

thumbs.slice(0,3).clone().appendTo("#thumbs");

This line essentially takes the first three thumbnails, copies them over to the end of the list. The slice method selects the first three elements, the clone methods clones these DOM elements and finally the appendTo methods adds them to the passed element.

We can’t just use the appendTo method since it plucks the selected elements from their current position before placing it as required. We need the clone method to copy them first.

We do this to make sure when we approach the final few thumbnails, the illusion of an infinite carousel remains. Else, the user just sees empty blocks which isn’t really what we need.

Making it Auto Rotate

Making the widget auto rotate is actually very simple. Since we have a proper event handler in place, we just have to call the handler every n microseconds. The following line will take care of that:

setInterval(sift, 8000);

In the above code, I’ve asked to call the sift function every eight seconds. Remember, the duration is passed in as microseconds so n thousand equals n seconds.

Initializing the Widget

Currently, the page loads with the widget uninitialized. We’ll need to rectify this. All we need to do is to call the show function passing in the starting position as a parameter.

After you’ve attached the event handler, add this:

show(index);

The Final Code

And we are done! The final code looks like so:

$(document).ready(function() 
{	 
	var index = 0;
	var images = $("#gallery img");
	var thumbs = $("#thumbs img");
	var imgHeight = thumbs.attr("height");
	thumbs.slice(0,3).clone().appendTo("#thumbs");
	for (i=0; i<thumbs.length; i++)
	{
		$(thumbs[i]).addClass("thumb-"+i);
		$(images[i]).addClass("image-"+i);
	}
	
	$("#next").click(sift);
	show(index);
	setInterval(sift, 8000);
	
	function sift()
	{
		if (index<(thumbs.length-1)){index+=1 ; }
		else {index=0}
		show (index);
	}
	
	function show(num)
	{
		images.fadeOut(400);
		$(".image-"+num).stop().fadeIn(400);
		var scrollPos = (num+1)*imgHeight;
		$("#thumbs").stop().animate({scrollTop: scrollPos}, 400);		
	}
});

Conclusion

And there you have it: we’ve created a simple but useful slider. Hopefully you’ve found this tutorial interesting and useful. Feel free to reuse this code elsewhere in your projects, and chime in within the comments if you are running into difficulties.

Questions? Nice things to say? Criticisms? Hit the comments section and leave me a comment. Happy coding!

Siddharth is Siddharth on Codecanyon
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • khaled

    wow nice I like it, thank you for the tutorial

    • http://icontut.com nabeel

      Yh its very helpful, it hard to find with this new laggy theme.

    • http://laranz.com lawrence77

      Siddharth always rocks :)

      Thanks for the tut sid ;)

    • http://www.complimedia.com Montana Flynn

      Best tut ever, and a great new theme to boot!

  • http://www.moscreative.com Serhiy

    yep nice tuts…. may I use it in my next project

    • http://www.ssiddharth.com Siddharth
      Author

      Yes, you may. :)

  • aryan

    Nettus css files are not being loaded. I checked it on several systems(I’m from India). Looks fine if I use proxy to browse this site.

    Please check if something wrong, else ignore my comment.

    • http://www.ssiddharth.com Siddharth
      Author

      Yep, I can attest to this error. The CSS files and images from the CDN aren’t available. Did S3 just blanket ban Indian IPs?

      • Michael Bryan

        It’s not just India, because it’s the same for me in America.

  • http://www.pingvps.com PingVPS

    Oooh this is a nice little effect to try, I’m gonna have a play with it and see if it comes in useful anywhere in some future projects.

    Many thanks.

  • http://www.themolitor.com Chris Molitor

    Fantastic! Are there any usage restrictions for this?

    • http://www.ssiddharth.com Siddharth
      Author

      Nope. Feel free to use it however you please.

      • http://www.themolitor.com Chris Molitor

        Thanks, you rock!

  • Anthony

    None of your tuts websites are loading the css files properly. You need to let us know whats up.

  • http://james.padolsey.com James Padolsey

    Instead of that for-loop-addClass(… i) thingy (lines ~8 to ~12), try using jQuery’s new setter function capability:

    thumbs.addClass(function(i){return ‘thumb-’ + i;});

    And why are you re-selecting each image in the “show” function? – $(“.image-”+num) – this would be more performant: images.eq(num)… Or, to make lines 27/28 more concise:

    images.fadeOut(400).eq(num).stop().fadeIn(400);

    Also, the variable “i” hasn’t been declared using a var statement, so it’s just floating around in the global namespace — not a good thing.

    Last, but not least, you should be caching your length property in the FOR loop – although the entire FOR loop can be axed if you follow the setter-function suggestion.

    • http://www.ssiddharth.com Siddharth
      Author

      I wasn’t aware of the setter function capability.

      Regarding re-selecting each image, I agree, your solution is much more succinct and elegant. I’ll keep these in mind when refactoring.

      Thank you for reading. I appreciate the feedback. :)

    • http://adrusi.com adrian

      the for loop seems more understandable…

  • Rebornmx

    Is there going to be a downloadable version of this tutorial for plus members?

    thanks,

  • http://mikebranski.com/ Mike Branski

    The demo’s throwing a ‘console is not defined’ error.

    Error: console is not defined
    Source File: http://nettuts.s3.cdn.plus.org/585_slider/demo/js/mocha.js
    Line: 39

  • Al

    working OK in FF

    button way down on screen on IE7

    Al

  • Spencer

    Love the tutorial, but the “Demo” and “Tutorial Image” (s) aren’t showing up? Been trying to check it out for an hour or so :( Still won’t load.

  • http://bigbuddymedia.com Buddy

    Any reason the demo and code links are throwing a 404? Is this just an issue on my end?

  • eric

    I think this is their first stab at telling IE7 users to drop dead!

  • http://www.jennamolby.com Jenna Molby

    WOW! Very nice, thanks for the great tutorial.

  • oconn96

    First of all, wicked awesome new look for tuts+.

    I was testing out the demo, when I click the down arrow are the thumbnails supposed to scroll or increment at all? Mine just stayed on the first three.

    • Rob

      It happened to me too! Using os x safari. After I reloaded the page it worked OK

      • oconn96

        I’m using Chrome right now and it doesn’t seem to be working in that respect. But it does in Firefox. Score one for them I guess :)

      • oconn96

        Alright, now we are in business. It just start working. Really cool effect, thanks for sharing.

  • http://www.milosmilikic.com Milos Milikic

    Nice tut! Thanks for sharing!

  • http://www.hellasconstruction.com Brendan

    Can this be done on php page?

    • http://www.flickr.com/photos/lorenzhs nuk

      sure. css and jacascript have nothing to do with php, so why would they conflict??? (step 1: switch on brain)

  • http://jmhale.com Joe

    Very useful, I see myself using this often.

  • http://www.cssispoetry.com Blake Tallos

    Sweet, thanks for the tutorial.

  • http://sonergonul.com Soner Gönül

    Cute..!

    Thanks very nice !

  • http://www.easypeasydesign.com nathan

    My first image slider! Many thanks.

  • http://www.easypeasydesign.com nathan

    sorry one thing, but to make the image auto rotate do I need to tweak anything? I changed the sift command to 2000 just to see the function in action but nothing happens. Thanks in advance!

  • Mike

    Not quite sure what is the point of showing thumbnails if you can’t click on them to select the next image you want to view?

  • Dom

    adding a return false; to the click function would prevent the browser from loading to the top when you click the anchor

    maybe not so much a problem in this example but good to keep in mind when implementing this

  • http://hontap.blogspot.com Rilwis

    Nice effect. But the right slider does not work in Opera 10.

    • http://www.ssiddharth.com Siddharth
      Author

      It may be the console.log line I put in for debugging. Can you try downloading the source files, comment that line out and try again?

      Thanks for reading. :)

  • tested

    The effect doesn’t work in Google Chrome. Works fine in Mozilla Firefox.

    • http://www.flickr.com/photos/lorenzhs nuk

      same for chromium 5.0.307.11 on linux

  • http://felixb.se/ Felix

    beautiful effect =) very nice

  • http://newfasttowing.com Hassan

    Hey Jeff! Why does the old posts appear at the top sometimes and sometimes the new ones appear? Why is that. Is it done purposely or is it like some mistake? It is kind of annoying though. Anyway to disable/fix that?

    Thanks a lot. Loving the design and everything.

    Especially the BASIX section. Everything is gathered in one place. I think you should also include the WordPress for designers series as well.

  • http://www.jhgraphix.com Janae

    This is absolutely awesome! I’ll definitely be putting the tutorial to good use when I role out my new portfolio layout – thanks!

  • http://prakasa.me/ Desainer web

    Now the demo work fine. Yesterday i cant see the demo.
    Thank’s for the tuts.

  • http://www.4shabwa.com khalid olaqy

    WOW! Very nice, thanks for the great tutorial.

  • http://www.foxyturkey.com Yigit Ozdamar

    I love it! I really love it! Thanks, it will be useful for my new design. ;) Peace!

  • http://adicahyono.com iwan

    ooohh very nice
    thank’s for the tutorial

  • http://art-altai.ru NerCrange

    Oh thank you!

  • http://www.webtint.net/ Johnny

    Really nice and easy to execute. I’m sure someone will find this useful in their new portfolio website somewhere :)

  • http://www.nouveller.com/ Benjamin Reid

    There’s been a few of these ‘slider’ tutorials recently, both being quite similar (given in this one there are a few smarter methods). How about loading in the images from a dynamic source rather than them being static, would make it great.

  • Andrea

    Un poco cutre no?

  • http://www.jordanwalker.net Jordan Walker

    Nice image slider, thanks for the tutorial

  • chandra

    There’s an issue with the code, the shell image fades away immediately after display.

  • wayno

    Very nice, just in time for a project I’m working on. Thanks!

  • http://www.pointydesign.com James

    THe vertical carousel isnt working for me, I’ve tried it in FF 3.6, Safari 4 anc Chrome. Any ideas?

  • http://spotdex.com Davidmoreen

    That is pretty nice slider. Looked like something I would use.

  • http://novatvmedia.com Anthony Alexander

    Yup. Carousel is aFUBAR. Also, There must be some way to condense this tutorial. It seemed to lack focus, but maybe because it’s directed at new guys? Not really a point, just a personal gripe.

  • Jules

    Can you make one with RSS???

  • RudraRSCA

    Hey mate,

    Great script. Tested on Opera 10 and IE8 and renders perfectly. Questionable on Chrome but that was mentioned earlier. Just a message of appreciation here, great work on the script.

    Regards.

  • naveen

    HI.. has any one used glider.js?

    http://www.jirehdesigners.com/hiddenplaces/

    if you go through the above mentioned website, you will see a small slideshow of books at the bottom right.
    I need to modify it but don’t know how to do it..
    When i slide to the last slide and again click the next all divs scroll to the first showing all the slides. When i click the next button it must be a loop and continuously slide like an infinite slidehow…

    Please respond immediately..
    thank you very much..

  • http://www.zlatoroh.com Zlatoroh

    Helo

    How can JavaScript be included at the end of the html file. I discovered it doesn’t work if JS is included in the header why is this so ? Is valid to include JS other than in header ?

    Great tutorial! Thanks!!

    Regards

  • http://ericcasequin.com Eric

    This is a wonderful tutorial, wish I found it earlier. I ended up doing something a different way before finding this tutorial on the home page of a site I worked on.

    http://ibethel.org/site/

    I do like the method/route you took though will take that in to account.

    Thanks for the awesome tutorial!

    -E

    • Nolan

      Hey Eric! I love the stability & cross-browser compatibility of your banner far better than this one, which I currently have implemented. What is the differences between yours and this one? (I want to make changes to mine) This one does not function properly in IE or Firefox and glitches often. Yours seems very stable in all browsers. LOVE IT!

  • http://soma.sidesph.com RaM

    I don’t know what I did wrong, but it seems that I can’t make it work on Firefox, though it is working on both IE and Crome. :|

  • ehsaan

    im trying to use this sideshow feature for a site but i cant seem to figure out what part of the code makes the code align to the center of the page, it keeps displaying the whole thing justified to the left.

    is it in the container part that refers to the css?