Making a Content Slider with jQuery UI

Making a Content Slider with jQuery UI

In this tutorial we’re going to be using the jQuery UI slider widget to create an attractive and functional content slider. We’ll have a container, which has a series of elements each containing different blocks of content. There will be too many of these elements to display at once, so we can use the slider to move the different content blocks in and out of view.


jQuery UI is the official library of widgets and utilities built on top of jQuery; it’s very easy to use, highly configurable and robust, and extremely easy to theme. To follow the tutorial you’ll need a copy of the latest version of the library; it can be downloaded using the jQuery UI download builder at http://jqueryui.com/download. Although we can choose any of the themes available, I’d recommend using the default theme of smoothness. jQuery UI includes a copy of the current version of jQuery, so we don’t need to download this separately.
Create a new folder somewhere handy and call it slider. Within this folder, create two new folders; one called jqueryui and one called images. Unpack the downloaded archive of the library to the jqueryui folder; in Explorer or Finder, you should end up with the following folder structure:

Folder Structure

Getting Started

Let’s make a start on the basic page and underlying HTML first; in your text editor create the following page:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>jQuery UI Slider</title>
    <link rel="stylesheet" type="text/css" href="jqueryui/css/smoothness/jquery-ui-1.7.2.custom.css">
    <link rel="stylesheet" type="text/css" href="slider.css">
  </head>
  <body>
    <div id="sliderContent" class="ui-corner-all">
      <h2>Some well known galactic nebulae and their vital statistics</h2>
        <div class="viewer ui-corner-all">
          <div class="content-conveyor ui-helper-clearfix">

          <div class="item">
            <h2>Omega Nebula</h2>
            <img src="images/omega.jpg" alt="Omega Nebula">
            <dl class="details ui-helper-clearfix">
              <dt>Distance from Earth:</dt><dd>5000 - 6000 lightyears</dd>
              <dt>Diameter:</dt><dd>15 Lightyears</dd>
              <dt>Mass:</dt><dd>800 solar masses</dd>
              <dt>Catalogue number:</dt><dd>M17 / NGC6618</dd>
              <dt>Discovered in:</dt><dd>1764</dd>
              <dt>Discoverer:</dt><dd>Philippe Loys de Chéseaux</dd>
            </dl>
          </div>

        </div>
      </div>
      <div id="slider"></div>
    </div>
    <script type="text/javascript" src="jqueryui/js/jquery-1.3.2.min.js"></script>
    <script type="text/javascript" src="jqueryui/js/jquery-ui-1.7.2.custom.min.js"></script>
  </body>
</html>

Save this as slider.html in the slider folder. In the head of the page, we link to the jQuery UI style sheet, which contains all of the CSS that’s required for each of the library components. It may seem like a waste; in some ways it is as we’re only using a single component, but using a 26KB style sheet. However, using a tool like YUICompressor, we can easily shrink this, and with GZipping too we can get it down even further. We also link to our own custom style sheet, which we’ll create later.

We haven’t added any styling yet but for reference, the following screenshot shows the default slider widget:

Slider Widget

The Underlying Mark-up

On the page all we have is the mark-up for the content and the slider; we’ve got an outer container element which we’ve given the class name ui-corner-all. This is one of the classes targeted by the jQuery UI style sheet and will give our container (and the other elements we give it to) nice rounded corners. It uses CSS3 to achieve this so not all browsers are supported, but Firefox, Safari or Chrome users will see them.

Within the container we’ve got a heading element that describes the content, followed by another container element (which will also have rounded corners in supporting browsers); when we come to add the CSS, this element will be given an overflow rule of hidden which will hide most of the individual content blocks and allow us to slide them into view using the slider. This element will function as the viewer.
Within the viewer we have a final container element; the reason for this is for performance – when we adjust the left CSS property with jQuery, we’ll only be selecting and manipulating one element instead of however many content blocks there are. We use another class name from the UI library on this element – the ui-helper-clearfix class, which automatically clears floated elements within whichever element it’s applied to.

Following this is an example of a content block; I’ve only shown one of them in the code example above because to show more would be unnecessary repetition. In the source file there are seven of them, but you can put as many in as you like and the slider will still function as it should. Each content block contains a heading, an image and a definition list, which semantically is probably the best choice for this example, but not necessarily required in other implementations. The content blocks can feature pretty much whatever they need to, provided each container is of a fixed size; you’ll see why this is important we come to add the JavaScript a little later on.

After the viewer element comes an empty container which will be transformed into the slider widget once we invoke the UI library. This is all underlying HTML that we’ll need. Following this we link to jQuery and to the jQuery UI source files; again, this file contains all of the JavaScript needed to run the whole UI library, which for this tutorial is more than we need. There are individual files for the core and each component separately which can cut down the footprint of the library. Both the jQuery and jQuery UI JS files are already minified.

Styling the Content

In truth we don’t need to worry about styling the slider widget itself at all; the theme that we downloaded with the library will do that for us. The CSS we’re about to add is pretty much purely arbitrary for the purpose of this tutorial, to tidy things up and give it a basic minimal look. As long as the individual content blocks (given a class name of item) are given a fixed width and are floated to the left within the conveyor element, and provided the viewer has its overflow set to hidden everything should work as expected.

In a new file in your text editor add the following code:

h2 { text-align:center; font:normal 150% Georgia; }
#sliderContent {
  width:650px; margin:auto; padding:0 50px 50px; background-color:#ebebeb;
  border:1px solid #898989;
}
.viewer {
  width:607px; height:343px; margin:0 auto 40px; padding:1px; overflow:hidden;
  position:relative; border:1px solid #898989;
}
.content-conveyor { width:610px; height:335px; position:relative; }
.item {
  width:304px; float:left; font-family:Tahoma; text-align:center;
  background-color:#ebebeb;
}
.item h2 { font-size:100%; margin:10px 0; }
.item dl { margin:10px 0; }
.item dt, .item dd {
  float:left; width:149px; text-align:right; margin:0; font-size:70%;
}
.item dt { font-weight:bold; margin-right:5px; }
.item dd { text-align:left; }
.item img { border:1px solid #898989; background-color:#ffffff; padding:1px; }

Save this as slider.css in the slider folder. Our page should now look like this:

Our page, so far

Adding the Slider Widget

All we need to do now is add the JavaScript that will initialise the slider and control our content blocks. Directly after the script element linking to jQuery UI in slider.html add the following code:

<script type="text/javascript">
  $(function() {

    //vars
    var conveyor = $(".content-conveyor", $("#sliderContent")),
    item = $(".item", $("#sliderContent"));

    //set length of conveyor
    conveyor.css("width", item.length * parseInt(item.css("width")));

    //config
    var sliderOpts = {
      max: (item.length * parseInt(item.css("width"))) - parseInt($(".viewer", $("#sliderContent")).css("width")),
      slide: function(e, ui) {
        conveyor.css("left", "-" + ui.value + "px");
      }
    };

    //create slider
    $("#slider").slider(sliderOpts);
  });
</script>

It’s a very short, simple snippet of code, with very little going on; let’s take a look at it line by line; Within the document.ready short-cut we first set up a few variables so that we can cache the elements from the page that we’ll be manipulating for performance reasons; this makes our code run faster because we’re only traversing the DOM and selecting each element once.

We select the conveyor element first of all by targeting its class name; because using a class selector is inefficient, we give the selector a context of the sliderContent element. The context is provided using an id selector, so the whole DOM does not need to be traversed. We also select the collection of content blocks in the same way.

Once we’ve cached our selectors we can set the length of the conveyor element; in the CSS it was set to the width of two of the content blocks, but for it to function correctly, the content boxes need to float alongside each other, so the conveyor needs to be wide enough to accommodate them all.

So that we don’t restrict how many content blocks can be put into the widget we don’t hardcode a set width into it; instead, we get the number of content blocks, and multiply this by the width of each block. This is why it’s important to set a fixed width on the blocks. We need to use JavaScript’s parseInt function when we retrieve the width of the blocks because the jQuery css method returns a string value in getter mode.

Next we create a literal configuration object which will be passed into the jQuery UI slider method and used to set some properties of the slider widget. Our configuration object has two properties, max and slide. The max property’s value is an integer which represents the width of the conveyor element minus the width of the viewer. This will be the maximum value that the slider handle can reach.
The value of the slide property is an anonymous function which will automatically receive two arguments; the original event object and a prepared object containing useful properties relating to the widget. We don’t use the first argument at all, which we define as e, but we need to include it to gain access to the second argument, which we term ui.

The slide event is a custom event exposed by the slider API, and the function we set as its value will be called each time a slide interaction occurs. Whenever the event is fired, we simply manipulate the left style property of our conveyor element negatively by the same amount as the slider is moved. We can get the value that the slider is moved to using the value property of the ui object.

We set the maximum value of the slider to the length of the conveyor element, in this example it ends up being 2128px, so the maximum value is 2128. This isn’t in pixels, as you’ll see in the next screenshot, the slider itself is around 650px in length. But, if we move the slider to about halfway along the track, the value reported in the ui object will be around 1064, so we move the left edge of the conveyor this many pixels to the left or right.

We don’t need to worry about detecting which direction the slider was moved in; if the slider handle has already been moved to the right, the left CSS property if the conveyor will already have a negative value. When we minus a negative number from a negative number, the outcome is of course a positive number so the conveyor will move back as it should. The completed page should now appear featuring the slider:

Completed Page

You should find that it works as expected and the different blocks of content can be moved in and out of view using the slider widget. As well as the standard drag interaction, also built into the slider is the useful addition of a click interaction; if click anywhere on the track, the handle is automatically moved to that position and the slide callback function is executed.

Conclusion

In this tutorial we’ve looked at how the underlying HTML used for the slider (a simple empty container), the default styling applied by the library, and how it can be configured and initialized with our code.

The slider is a great addition to any interface; it’s easy for us to set up and easy for our visitors to use, it’s tactile and interactive and can be used in a variety of situations from moving content around like in this example, or as, say, a volume control on a streaming web app.


Add Comment

Discussion 140 Comments

Comment Page 2 of 3 1 2 3
  1. Very nice man!

    I was implementing this in one of my sites but I’ve found a problem when I added a margin and a padding to the div.item …

    I don’t know if someone else had the same problem but here is my solution:
    (I have to clean it now)

    [...]
    //set length of conveyor
    var margins = 42; //you can get this parsing the margins and padding values at the same way as others
    var itemn = parseInt(item.css(“width”));
    var itemm = itemn + margins;
    conveyor.css(“width”, item.length * itemm);

    //config
    var sliderOpts = {
    max: (item.length * itemm) – parseInt($(“#content-wrapper”).css(“width”)),
    [...]

    hope you find this useful..

  2. chromax says:

    It needs easing!

  3. This tutorial made me sad. :(

    The slider component is meant to be used as a form control, NOT as a replacement for a scroll bar. I realize you’re just trying to demo jQuery UI functionality, but Front End Engineering isn’t just about making the code work, and examples that encourage bad usability are bad for everyone.

  4. Edward says:

    Hello,
    Is there an alternative way to scroll the content as opposed to using a negative “margineLeft” or simple a negative “left” for a relatively positioned element.
    For example. can we use the scrollTO plugin somehow to achieve that?

    Please help me. I need this for my page (http://www.tomngo.net/arch1k/archives/category/academic) where i’m trying to use both the locallScroll and serialScroll plugins to make the “next” and “prev” buttons.

    so yes. i wanna have both – a custom scrollbar and a cyclins slider effect.

    Your help would be greatly appreciated. I’ve been trying to crack this problem for 3 days now!

  5. Roger says:

    Has anyone added Auto scroll snippet to this yet? I would love to see one that fits nicely into this sweet java scroller

    • kapgun says:

      I would also be very interested in an “autoscroll” feature. I would like to make the slide scroll left or right when the mouse is brought to left or right edge of the slider content area. How would I go about doing this?

      Thank you,

  6. Is there a way to combine the slider with a lightbox effect so if I have a link in one of the s it open the content (flash mp3 player) with the lightbox effect?

  7. kula says:

    how would you go about making the scrollbar a set width like 200px wide but my image viewing area is like 800px wide, appreciate the help

    Thanks!!!!!

  8. optimus says:

    hey can anyone help me the same thing in vertical slider……
    I tried this http://docs.jquery.com/UI/Slider#options
    but some parameters are getting wrong………..

    If anyone can, then really appreciated….

  9. Roygbiv says:

    I’m new to all this and have been playing around with it but would love to know how to show a div if the value hits a certain level and hide otherwise. This doesn’t seem to be working:

    slide: function(e, ui) {
    conveyor.css(“left”, “-” + ui.value + “px”);
    $(“#amount”).val(‘$’ + ui.value);

    if ($(“#slider”).slider(“value”) == ’304′) {
    $(“#test”).show();
    } else {
    $(“#test”).hide();
    }

    Any ideas what I’m doing wrong?

  10. rugbert says:

    Ok so this is pretty cool but Im trying to get it to work vertically. I set the orientation to vertical and took the float off the items so that they SHOULD scroll up BUT Ive run into two issues.

    First, the slider starts at the bottom of the track. AND pulling the slider up makes things scroll down when I set conveyor to “top”.

    Its this line I need to change right?:
    slide: function(e, ui) {
    conveyor.css(“top”, “-” + ui.value + “px”);
    }

  11. thinkbliss says:

    This is a great tut but I found one Safari bug I can’t figure out how to fix. I need all the items to have a width: auto; but Safari doesn’t like that and will display what seems like the last item with the scroll handle position at the end which also breaks the scroll.

    Anyone have any ideas?

    Thanks

  12. lukas says:

    very great tut. Thanks for sharing.

  13. Nice one mate. I have also added the link to your post in my Ultimate

    collection of top jQuery tutorials, tips-tricks and techniques to improve

    performance. Have a check below:

    http://technosiastic.wordpress.com/2009/09/24/collection-of-top-jquery-

    tutorials-tips-tricks-techniques-to-improve-performance/

  14. elmolulu says:

    Hi, thank you for this wonderful tutorial. I was trying to create something like the apple’s slider. There is another jquery tutorial out there, but it only works with older version of jquery. Would it be possible for you to show me how to add labels in the scroll bar so that when you click on the label, it will jump to that section accordingly? Your help is greatly appreciated!

  15. Gunpower says:

    Hi,

    Thanks for the great tutorial!
    Is it possible that you make one with mysql?
    I would really appreciate that!

    Greetz!

  16. droomagon says:

    any idea when you click on the block (on the scrollbar), it would slightly jump? how can i fix that ?

  17. jesudas says:

    Hi Dan wellman,

    As per name ur doing good job…

    I have used in my site…its amazing..but problem is i have add 16 itmes but it only show 13 only..

    if i am adding 12 its only show…9 …

    what may be the issue…

    please help…wellman…

  18. jesudas says:

    hey..well man….

    I have found one bug..which was just on mind while implementing…the ur code…

    that when u add new items or list to the ur slider…its only count the width of the list/content/item….its not adding the lmargin and padding…which i have add for my purpose….

    thanks and reagrds

  19. Wojciech Twardowski says:

    You might want to replace
    “conveyor.css(“width”, item.length * parseInt(item.css(“width”)));” and
    “max: (item.length * parseInt(item.css(“width”))) – parseInt($(“.viewer”, $(“#sliderContent”)).css(“width”)),” with:
    ” conveyor.css(“width”, item.length * (parseInt(item.css(“width”)) + parseInt(item.css(‘paddingLeft’)) + parseInt(item.css(‘paddingRight’))));” and
    ” max: (item.length * (parseInt(item.css(“width”)) + parseInt(item.css(‘paddingLeft’)) + parseInt(item.css(‘paddingRight’)))) – parseInt($(“.viewer”, $(“.products-list”)).css(“width”)),”.
    I spent a lfair amount of time trying to figure out why the last item won’t show ;)

  20. Indialike says:

    Very nice and useful tutorials for web designers,
    Thanks for posting.

  21. john says:

    i am a chinese, i love wordpress, but i find there’s no such userful plugin can be used on wordpress. thanks for your works, if you can deveople the wp plugin of this, it will be great!

  22. john says:

    i love wordpress, but i find there’s no such userful plugin can be used on wordpress. thanks for your works, if you can deveople the wp plugin of this, it will be great!

  23. param says:

    Hey Dan,

    This is a really good utility.
    There is, however, an issue when I am trying to implement the content slider inside an ajax div.

    i.e. creat the slider in a page say slider.php and then load slider.php in a div on another page
    $(“#divslider”).load(“slider.php”);

    JS Errors
    Line: 117875032
    Error: Invalid argument.

    Line: 117875022
    Error: Object doesn’t support this property or method

    Have you ever come accross these errors earlier?

    Thanks

  24. rajesh says:

    great tutorial….
    this is what i am exactly looking for………..
    thank you so much for sharing this ……….

  25. Kev says:

    Wondering how we can implement Vertical slider!!!

    Cheers.

  26. Arff says:

    How would you make a full width slider that always fits a 100% width of the window and adjusts on resize? Any ideas or advice? Thanks!

  27. Kenny says:

    I modified the script to allow you to select which item it starts on. It will automatically compensate for padding now too, provided that you set it using padding-left and padding-right in the stylesheet. Hopefully this will save someone some time.

    $(function() {

    // Desired starting position (Can be made dynamic serverside)
    var desiredPosition = 4;

    // Reference to items
    item = $(“.item”, $(“#sliderContent”));

    // Item padding (extracted from CSS)
    var padding = parseInt(item.css(“padding-left”)) + parseInt(item.css(“padding-right”));
    // Item width (extracted from CSS)
    var itemWidth = parseInt(item.css(“width”));

    // Reference to conveyor element
    var conveyor = $(“.content-conveyor”, $(“#sliderContent”));

    //set length of conveyor
    conveyor.css(“width”, item.length * (itemWidth + padding));

    // Computed max slider value
    var sliderMax = (item.length * (itemWidth + padding)) – parseInt($(“.viewer”, $(“#sliderContent”)).css(“width”));

    // Value of desired initial position
    var v = (itemWidth + padding) * (desiredPosition – 1);

    // Set initial conveyor position to show desired item
    conveyor.css(“left”, “-” + v + “px”);

    //config
    var sliderOpts = {
    value:v,
    max: sliderMax ,
    slide: function(e, ui) {
    conveyor.css(“left”, “-” + ui.value + “px”); // Whenever slider moves, adjust conveyor to new position
    },
    };

    //create slider
    $(“#slider”).slider(sliderOpts);
    });

  28. Web Dizajn says:

    Great Job. THX from Sarajevo!

  29. vainfotech says:

    It is very Useful for me and i am also web developer in ahmedabad.

  30. Hagge says:

    Hi Guys,

    Is there a way to fix this to work on iPads?

    Thanks!

  31. Eza says:

    This is a great tutorial !
    exactly what I was looking for.

    Question: How can I put multiple slider on 1 page?

    Thanks!

  32. I too am also wondering how you can have multiple sliders on one page. I’m using this to scroll multiple rows of products for an e-comm site.

    Anyone, please…

  33. MysteryE says:

    Yes, I also want to put 3 slider at once in 1 page, side by side. Is that possible?
    Do we have to change all of “ID” to “class”?

  34. Vitaliy says:

    Looks really great.. But can it be used on wordpress? It don’t works with WP…
    PS. Great work, thank you for share it!

  35. darja says:

    great tut, thanks!
    but what if I can’t set fixed width of the blocks (pictures), because each of them has its own width?
    I’ve tryed but extra white space appears at the end of conveyor — how can I solve it?
    and one more little question, sorry: the length of the slider needs to be as long as conveyor?
    thanks a lot!

  36. vijay says:

    1. h2 { text-align:center; font:normal 150% Georgia; }
    2. #sliderContent {
    3. width:650px; margin:auto; padding:0 50px 50px; background-color:#ebebeb;
    4. border:1px solid #898989;
    5. }
    6. .viewer {
    7. width:607px; height:343px; margin:0 auto 40px; padding:1px; overflow:hidden;
    8. position:relative; border:1px solid #898989;
    9. }
    10. .content-conveyor { width:610px; height:335px; position:relative; }
    11. .item {
    12. width:304px; float:left; font-family:Tahoma; text-align:center;
    13. background-color:#ebebeb;
    14. }
    15. .item h2 { font-size:100%; margin:10px 0; }
    16. .item dl { margin:10px 0; }
    17. .item dt, .item dd {
    18. float:left; width:149px; text-align:rightright; margin:0; font-size:70%;
    19. }
    20. .item dt { font-weight:bold; margin-right:5px; }
    21. .item dd { text-align:left; }
    22. .item img { border:1px solid #898989; background-color:#ffffff; padding:1px; }

  37. JD says:

    Great tutorial!
    Though I can seem to get it to work on sharepoint…
    I have modified the look and it seems to work great in dreamweaver. But when embeded into a webpart the scroll bar dissappears. Any idea where to start?
    Thanks

  38. Eastern Block says:

    Great explanation of the slider’s anonymous function. This was very informative and easy to build.

  39. Hendrik says:

    Thanks. Was trying something like this forever. Your slider tutorial made my day.

  40. AMTT says:

    Thanks a lot for this great article, youre the best.
    It works :-)

  41. SAWYER says:

    i want to add a tooltip to a slider ……. ane1 can help me with the code n demo..???

  42. James says:

    How would I go about changing the length of the “conveyor”.

    According to this article is it set at 2128:
    “maximum value of the slider to the length of the conveyor element, in this example it ends up being 2128px, so the maximum value is 2128″

    I need each item to be the width of 600px plus a margin-left & margin-right of 100px.

    Here is the CSS I’m trying to get to work w/o the items breaking to a new line:

    #sliderContent { width:1000px; margin:auto; padding:100px 0; border:1px dashed #898989; }
    .viewer { width:998px; height:500px; margin:0 auto 40px; overflow:hidden; position:relative; }
    .content-conveyor { width:900px; height:335px; position:relative; }
    .item { width:600px; height: 300px; float:left; margin: 0; }
    .item h2 { margin:10px 0; }
    .item dl { margin:10px 0; }
    .item dt, .item dd { float:left; text-align:right; margin:0; }
    .item dt { font-weight:bold; margin-right:5px; }
    .item dd { text-align:left; }
    .item img { background-color:#ffffff; padding:1px; }
    #slider { width: 600px; margin: 0 auto; }

  43. Kumar Desai says:

    Works great in all browsers except in IE9. The demo doesn’t work in IE9 either. Otherwise very nice.

  44. Andrzej says:

    Great tutorial, is it possible to customize the slider to such a beautiful and simple form: http://www.popcultureonline.it/Basico/Default/product-page.html

  45. Jose Carlos says:

    I want to add “backward” and “forward” buttons at the ends of the slider, but I dont know how, can you help me.

  46. Coupons says:

    Thanks tutsplus. I really need a content slider like this.

  47. Vertical Scrollbar Tutorial pls!! says:

    Can you please add a tutorial on a vertical scrollbar

Comment Page 2 of 3 1 2 3

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.