Scrolling Content with jQueryUI Slider

February 5th, 2011 / Code

My first step when thinking of ways to create scrollable content was a Google search that lead me to a good post outlining how to use jQueryUI Slider to scroll a div. This solution required altering the jQueryUI source, which I felt was unnecessary, so I came up with a simple solution.

Slider interactions

There are two different interactions with the slider: clicking anywhere on the slider, and dragging the slide head. When clicking on the slider you want the slide head and content to smoothly animate to the clicked position. When dragging, you want the content to match the slide head position 1:1. Here’s an example of both:

Scrolling content example.

Scrolling content example.

Simple setup

The HTML is very simple. Inside a parent container is the scroll content and the slider, and the content is an unordered list:

<div class="scroll-container">
  <div class="scroll-content">
  <div class="scroll-slider"></div>

The JavaScript for the slider:

// Variable to hold scroll type
var slideDrag,
// Width of .scroll-content ul
slideWidth = 330,
// Speed of animation in ms
slideSpeed = 400;

// Initialize sliders
  animate: slideSpeed,
  start: checkType,
  slide: doSlide,
  max: slideWidth

function checkType(e){
  slideDrag = $("ui-slider-handle");

function doSlide(e, ui){
  var target = $(".scroll-content"),
  // If sliders were above the content instead of below, we'd use:
  // target = $(".scroll-content")
  maxScroll = target.attr("scrollWidth") - target.width();
   // Was it a click or drag?
  if (slideDrag == true){
    // User dragged slider head, match position
    target.attr({scrollLeft: ui.value * (maxScroll / slideWidth) });
    // User clicked on slider itself, animate to position
        scrollLeft: ui.value * (maxScroll / slideWidth)
    }, slideSpeed);

When the slider is clicked, the function checkType() is executed, which determines if the handle or the slider was clicked. This determines which type of animation to do.

The other benefit of setting the code up like this is that I can have multiple sliders on the page that are all controlled with this single function. The piece that makes that possible is var target = $(".scroll-content"), which says we’re going to animate the content directly above the active slider in the DOM.

Scrollable content demo

The demo has six scrollable content divs, all controlled by the JavaScript above: