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">
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
      <li>4</li>
      <li>5</li>
      <li>6</li>
      <li>7</li>
      <li>8</li>
    </ul>
  </div>
  <div class="scroll-slider"></div>
</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
$(".scroll-slider").slider({
  animate: slideSpeed,
  start: checkType,
  slide: doSlide,
  max: slideWidth
});


function checkType(e){
  slideDrag = $(e.originalEvent.target).hasClass("ui-slider-handle");
}

function doSlide(e, ui){
  var target = $(e.target).prev(".scroll-content"),
  // If sliders were above the content instead of below, we'd use:
  // target = $(e.target).next(".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) });
  }
  else{
    // User clicked on slider itself, animate to position
    target.stop().animate({
        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 = $(e.target).prev(".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: