How to Create a Simple iTunes-like Slider
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.
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.
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.
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!
- Follow us on Twitter, or subscribe to the Nettuts+ RSS Feed for the best web development tutorials on the web.