spacer

Using jQuery Slider to Scroll a Div

Skill
spacer
spacer

Using jQuery Slider to Scroll a Div

Posted in:
  • Tutorials
  • CSS
  • jQuery
  • HTML
  • Javascript

Today's tutorial is going to show how to create a horizontally scrolling div using jQuery, html, and css. The main part of this tutorial is going to focus on the jQuery which is used to build the slider which controls the scrolling. One of the first questions that is going to pop into your head is, "why?". Well the main reason to do this is to be able to build a custom scroll bar/slider. You can also introduce extra functionality using the jQuery slider.

To get this started go ahead and check out the little demo below. There isn't anything real hard to figure out with the demo. One nicety to check out is the ability to click on the scroll bar anywhere and the div will do an animated scroll to that position. Just as a note, I have noticed a small bug with the jQuery slider where it doesn't always get the end position correct when you click on the scroll bar. Well, take a second and bask in the glory of the scrolling area below.

Lorem ipsum dolor sit amet, ut turpis sagittis, nec placerat, molestie convallis. Mattis et delectus, nullam cras et, faucibus ultrices. Nunc elit, tellus vulputate eros. Leo wisi, luctus pretium. Platea arcu, in natoque non, ipsum eu vivamus.

Justo dictumst, aliquam metus. Libero sed vivamus, cursus felis etiam. Eu nonummy vestibulum, class excepturi. Nulla tincidunt urna. Phasellus ac lacus, sit eu massa. Velit pretium purus. Rem ac porta.

Lorem ipsum dolor sit amet, ut turpis sagittis, nec placerat, molestie convallis. Mattis et delectus, nullam cras et, faucibus ultrices. Nunc elit, tellus vulputate eros. Leo wisi, luctus pretium. Platea arcu, in natoque non, ipsum eu vivamus.

Justo dictumst, aliquam metus. Libero sed vivamus, cursus felis etiam. Eu nonummy vestibulum, class excepturi. Nulla tincidunt urna. Phasellus ac lacus, sit eu massa. Velit pretium purus. Rem ac porta.

Lorem ipsum dolor sit amet, ut turpis sagittis, nec placerat, molestie convallis. Mattis et delectus, nullam cras et, faucibus ultrices. Nunc elit, tellus vulputate eros. Leo wisi, luctus pretium. Platea arcu, in natoque non, ipsum eu vivamus.

Justo dictumst, aliquam metus. Libero sed vivamus, cursus felis etiam. Eu nonummy vestibulum, class excepturi. Nulla tincidunt urna. Phasellus ac lacus, sit eu massa. Velit pretium purus. Rem ac porta.

Lorem ipsum dolor sit amet, ut turpis sagittis, nec placerat, molestie convallis. Mattis et delectus, nullam cras et, faucibus ultrices. Nunc elit, tellus vulputate eros. Leo wisi, luctus pretium. Platea arcu, in natoque non, ipsum eu vivamus.

Justo dictumst, aliquam metus. Libero sed vivamus, cursus felis etiam. Eu nonummy vestibulum, class excepturi. Nulla tincidunt urna. Phasellus ac lacus, sit eu massa. Velit pretium purus. Rem ac porta.

Lorem ipsum dolor sit amet, ut turpis sagittis, nec placerat, molestie convallis. Mattis et delectus, nullam cras et, faucibus ultrices. Nunc elit, tellus vulputate eros. Leo wisi, luctus pretium. Platea arcu, in natoque non, ipsum eu vivamus.

Justo dictumst, aliquam metus. Libero sed vivamus, cursus felis etiam. Eu nonummy vestibulum, class excepturi. Nulla tincidunt urna. Phasellus ac lacus, sit eu massa. Velit pretium purus. Rem ac porta.

Ok, now let's get coding. We are first going to start with the basic html setup of the demo above. This shouldn't look like anything crazy. The first element I pretty much always add to wrap my content is a div. We then setup the slider div, the handle will be created for us. Next up is a div to scroll and inside a div wide enough to hold the content. And lastly the content, which in my case is a bunch of divs. This ends up looking like the following (minus the content).

<div id="main">
<div id="content-slider"></div>
<div id="content-scroll">
  <div id="content-holder">
    <div class="content-item">
    </div>
    <div class="content-item">
    </div>
    <div class="content-item">
    </div>
    <div class="content-item">
    </div>
    <div class="content-item">
    </div>
  </div>
</div>
</div>

To complete the html part we need to add some css to make things look as they should. After the code I will go over it.

#main {
  width: 510px;
  margin: 0 auto;
}

#content-slider {
  width: 490px;
  height: 6px;
  margin: 5px;
  background: #BBBBBB;
  position: relative;
}

.ui-slider-handle {
  width: 8px;
  height: 14px;
  position: absolute;
  top: -4px;
  background: #478AFF;
  border: solid 1px black;
}

#content-scroll {
  width: 500px;
  height: 300px;
  margin-top: 10px;
  overflow: hidden;
  border: solid 1px black;
}

#content-holder {
  width: 1500px;
  height: 270px;
}

.content-item {
  width: 290px;
  height: 270px;
  padding: 5px;
  float: left;
}

Starting at the top we simply set the width the main wrapper. Then we set the size of the slider bar, we also have to set the position to relative (a must have). For the handle we set the size and more importantly the position to absolute. For the scrolling div we set the size to a visible area we want. To make sure the content is hidden beyond that we set overflow to hidden. The inside content holder needs to be wide enough to hold all of the content horizontally. Finally the content items themselves need to float left in order to keep moving horizontally.

We can start working with jQuery (1.3.2) now that we have everything setup. We also need to use some jQuery UI script so I built a custom script that included two pieces the UI Core and Slider Widget.

To get things moving let's take a look at the code to setup the slider. Using the basic jQuery setup function $(document).ready() we build our slider. To do this we use the function slider called off of the selector for the slider element. The options we pass are an object with animate, change, and slide properties set. The change property is set to the function that will be called when the slider value changes and the slide property is set to the function that is called when the slider handle moves. The creation code is below, we will add the event handlers after.

$(document).ready(function(){
  $("#content-slider").slider({
    animate: true,
    change: handleSliderChange,
    slide: handleSliderSlide
  });
});

The two handle functions are below, I will go over the code after.

function handleSliderChange(e, ui)
{
  var maxScroll = $("#content-scroll").attr("scrollWidth") -
                  $("#content-scroll").width();
  $("#content-scroll").animate({scrollLeft: ui.value *
     (maxScroll / 100) }, 1000);
}

function handleSliderSlide(e, ui)
{
  var maxScroll = $("#content-scroll").attr("scrollWidth") -
                  $("#content-scroll").width();
  $("#content-scroll").attr({scrollLeft: ui.value * (maxScroll / 100) });
}

The first line of both event handlers calculates the maximum scroll value, which is equal to the scrollWidth minus the width of the div. Then for the change event we animate the div scrolling using the jQuery core animate function. Then for the slide event we simply set the scrollLeft value. To calculate we use the slider value (defaults to value of 0 to 100) and the max scroll to figure out the scroll offset.

Well that pretty much takes care of all the code. You can download all the demo slider application files and if you have any questions feel free to ask. Until next time, keep coding and keep reading SOTC. Also note that the demo was tested in FF2, FF3, Opera 9.6, Safari 3.1.2, IE 6, and IE 7.

Also if you're looking to dive into jQuery some more or just looking for a quick solutions to common problems, check out jQuery Cookbook: Solutions & Examples (See all Web Programming Books).

Edited May 11 2009

Code has been updated to work with jquery 1.3.2 and jquery UI 1.7. The example project has been updated as well. The example above is still using older code.

Edited June 18 2009

For jQuery UI 1.7.2 in order to get smooth scrolling when clicking on the scroll bar you need to update ui.slider.js and replace the following:

var allowed = this._trigger("slide", event, {
    handle: this.handles[index],
    value: newVal
});

with

if(event.type   == 'mousemove') {
    var allowed = this._trigger("slide", event, {
        handle: this.handles[index],
        value: newVal
    });
}

Thanks, to hiKrittiya for providing this update.

Want to learn more about jQuery? Check out these great books:

161 comments

Gordon McNeil
10/24/2008 - 21:46

Your link to the "demo sler aspplication files" does not work.

How do I get a copy of your slider code?

Thanks.

reply

spacer
The Tallest
10/24/2008 - 21:58

Sorry, there was a typo in the link - it is fixed now.

reply

Tomas
11/07/2008 - 09:16

Thanks a lot for the cool code. This is one of few jQuery scrollers I have found that actually works smoothly in all browsers. Well done!

Now I am trying to change the scroll-handle to be an icon instead. Wish me good luck.

Tomas

reply

Jared
11/08/2008 - 02:29

What if you only have 3 content-items and have all this extra white space?

Is there something that can be tweaked with the coding to scroll to the length of the last div?

reply

Veera
11/11/2008 - 23:26

Very useful JQuery script.

reply

Andy
11/15/2008 - 09:23

Great app. How do I make it scroll down instead of to the left? I feel like I've changed all the css to do this. But I'm not certain where to start with the jQuery scripts.

Thx

reply

Phil
11/16/2008 - 09:52

That is really nice. I too would like to see how to make is scroll vertically. Nice work.

reply

Mark
11/17/2008 - 18:35

is there a way to use this script but to not have to set the width of the container div (content-holder). I would like to use the scroller for a site running off of a cms - so I can't preset the width because the amount of content will be changeable.

reply

gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.