Using jQuery Slider to Scroll a Div

Skill

Using jQuery Slider to Scroll a Div

Posted in:

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.

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

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

Henry
11/24/2008 - 23:39

The code works, thanks for your blog.

reply

Chris
11/25/2008 - 12:05

Hi, great script! thank you! I w as wondering if you could tell me how to get the slider bar centered under the box? I've shortened it but it aligns on the left. Would love to have it centered.

Thanks, -Chris

reply

Chris
11/25/2008 - 12:06

link to my page is here:
http://tattoodesignmall.com/index.php?main_page=index&cPath=2

reply

Amy
12/09/2008 - 12:48

Thanks for the tutorial!

When you refresh the page, the div content doesn’t start back at the starting point to the left like the handle does. Is there a way to make this happen?

Also, is there a way to make the slider snap to step points while retaining the smooth scrolling effect?

@mark: assuming all the content-item divs are equal width, you can make it work without knowing the exact width of the content holder. What I did was calculate the amount of child divs in the content holder. Then, since I knew the width of each content-item div i set $(”#content-holder”).css(”width”, childWidth * amountOfChildren

My example is at http://static.spartaninternet.com/sandbox/

reply

Larry
01/26/2010 - 17:11

The issue with the slider not being reset to its correct position along with the div can be corrected using the following bit of code

$(document).ready(function(){
        $("#content-slider").slider({ animate: true, change: handleSliderChange, slide: handleSliderSlide });
        var content_scroll_pos = Math.floor(($("#content-scroll").scrollLeft() / $("#content-scroll").width()) * 100);
       
        if ($("#content-scroll").scrollLeft() != 0) { $("#content-slider a").css("left",content_scroll_pos+"%"); }
});

Great script, thanks again.

reply

Larry
02/19/2010 - 14:47

correction to above:

var content_scroll_pos = Math.floor(($("#content-scroll").scrollLeft() / ($(".wall").width() - $("#content-scroll").width())) * 100);

reply

SerzN1
04/21/2010 - 04:45

what is the ".wall" ?

reply

Anonymous
03/03/2010 - 22:58

amy, i a noob, can you please show me where to insert the code to make it work. Thanks in advance

reply

sam
03/04/2010 - 19:56

someone please help me. i need to know how to make this script work without defining the width of the scroll. amy showed the script addition but i dont know how to implement it. im a noob. please help!!! really nice script btw

reply

Diego
12/17/2008 - 07:11

And is there any way to make it works if you don’t have javascript active?, i mean unobtrusive javascript.

Thanks in advance.

reply

Diega
12/29/2008 - 08:09

Sorry for the stupid question but how can I use this scroll for vertical content?

reply

Txo
01/03/2009 - 10:24

I have 50 “content-item” and scroll is very fast.
How to reduce scroll speed

reply

saagar
01/22/2009 - 08:50

Great! helpful for us!!!!!!!!!!!!!!!

reply

MacAttack
04/10/2009 - 13:08

Hi! Great script...

I was just wondering how I might be able to make the scrolling action a bit smoother. Are there any options or plugins that might help make the scrollbar a bit more responsive and smooth?

Thanks!

reply

The Fattest
04/13/2009 - 10:13

Are you talking about the content scrolling more smoothly or the scrollbar itself? For the more responsive part can you include an example that illustrates what you're looking for?

reply

Salman
05/06/2009 - 10:03

Hi Fattest

great tutorial
but does not work with latest build of jquery.

can you please amend it for new jquery i have tried many times but failed i hope you can get it to work with JQ1.3 above.

Regards
Salman

reply

The Fattest
05/06/2009 - 12:15

Yes, I will do this today at some point and update the post above.

reply

Salman
05/07/2009 - 14:49

Hi Fattest

Thanks mate for quick response,
looking forward to it, i want to implement this idea into one of my apps so keenly waiting for the update.

also when i try to post a reply from google chrome i get an error saying

"Your hashcash string is not valid. Are you a spammer?"

Regards
Salman

reply

The Reddest
05/07/2009 - 14:54

Thanks for the comment reply bug. I just tried using Chrome to reply and had no issues (both logged in and not logged in). The comment system requires javascript to be enabled when you're not logged in. Is there a chance you've got javascript disabled?

reply

Salman Sadiq
05/07/2009 - 15:05

Wow

you guys are fast with responses
i think javascript is enabled, can you disable javascript in chrome?

lets try to send this comment from chrome instead of fox

and what about the tutorial being compatible with JQ1.3

salman

reply

The Reddest
05/07/2009 - 15:08

You know, I actually don't think you can disable JS in Chrome. It looks like the comment worked though, so maybe that was a one-time glitch. I'll have to check out our HashCash module. As far as the tutorial working on JQ1.3, that's all up to The Fattest. I'm sure he's on it though.

reply

M Salman
05/09/2009 - 13:18

Well guys its my 4th and final attempt to send comment and i have tried chrome, IE7, Firefox3 all said
"you hascash is not valid are you a spamer".

fattest iam still waiting foe the tutorial to be updated for jq1.3

salman

reply

arachnid
05/10/2009 - 09:41

It is not working properly with jquery v1.3.2 and 1.7.1. The content is moving but the handle remain fixed

reply

The Fattest
05/11/2009 - 09:33

Sorry for the delay but the code has been updated to jquery 1.3.2 and ui 1.7.1. Let me know if you have any issues.

reply

Peachy
05/26/2009 - 11:24

Hi, I've tried the latest version of this (downloaded your demo files) and there do seem to be some bugs using jquery1.3.2 and ui 1.7.1. I've been testing in FireFox 3 and Safari on the Mac.

Are you aware of any bugs?

reply

Anonymous
05/16/2009 - 15:49

Hi there,

I am using this script, making a portfolio,
here is a snippet, explaining the problem:

bkinfo.bk.tudelft.nl/portfolio/websites/jvanommeren/Third%20website/slider_test.html#

the problem is that the slider only appears at the first loaded item.

I am pretty new to jquery, probably, I need to make some sort of generic piece of code, but I dont know how...

Thanx!

reply

The Fattest
05/18/2009 - 21:11

I think this is probably because of the multiple sliders and your using the same id for every slider. This is going to confuse javascript. If you would like I can put up a sample using multiple sliders?

reply

Anonymous
10/23/2009 - 12:06

How do I edit the javascript code if I'm using multiple sliders? Any help would be very much appreciated, thank you in advance.

reply

Sheldon
05/20/2009 - 22:23

First, nice piece of code!

I have an interesting issue...I'm using this to scroll my news and everything works well in FF, Chrome and Safari, in IE however the floated item elements remain stationary when I scroll the div.

Any ideas why or how to fix?

My sandbox page: http://newsite.aquanode.com/news

Thanks in advance and again nice work.

reply

leluch
05/21/2009 - 01:28

Hi,

Nice work. How can i make it to scroll vertically instead of scrolling horizontal?

Thanks

leluch

reply

hiKrittiya
06/12/2009 - 01:02

Very nice work! I downloaded your slider_example which uses jquery 1.3.2 and ui 1.7.1. and tested it.
It works fine when I drag the blue handle. However,if I click anywhere on a grey track, the content doesn't scroll /animate properly. Sometimes the content jumps without animation and sometime with animation.

I found a similar issue when I tried the tutorial I found below with jquery 1.3.2 and ui 1.7.1 http://jqueryfordesigners.com/slider-gallery/

I'll revisit your site to see if you find any solution to fix it.
Thanks again :) !!!!

reply

The Fattest
06/12/2009 - 12:43

I will check it out, probably won't get to this until tonight though.

reply

hiKrittiya
06/16/2009 - 10:51

hi The Fattest.
Thank you for your response. Did you get a chance to look and find a solution to the unsteady animation (when clicking the track)? I wonder if this is caused by a conflicting logic in the two callback functions ( slide and change) .
For example, whenever the track is clicked, the handleSliderSlider function will always be executed before handleSliderChange function. The code in the handleSliderSlider function tells the content-scroll to move without animation. Then, the handleSliderChange tells content -scroll to move with animation BUT the content -scroll was already moved before.

Is there a way to stop handleSliderSlider from being executed when the track is clicked?

If my assumption makes sense, I wonder why this is not an issue in older jquery ui 1.2.x ( the demo embedded on this page shows a perfect smooth animation when clicking the track).

I'm new to jQuery but found your resource very useful. Thank you in advance!

reply

The Fattest
06/16/2009 - 15:03

Yeah I played around with a little bit, I will try and come up with solution quickly.

reply

hiKrittiya
06/17/2009 - 16:43

hi again :)
I found the answer that someone posted from
http://jqueryfordesigners.com/slider-gallery/
and want to share.

//Using jQuery ui 1.7.2
the ui.slider.js: needs to be modified. from

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

to

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

This prevents the slide function from being triggered when clicking the slider ( track).

reply

The Fattest
06/17/2009 - 17:40

awesome stuff, I assumed it was something of mine and hadn't started combing through their code yet. I will add an edit to the post about it.

reply

Anonymous
07/02/2009 - 23:44

ui.slider.js ? For all those who don't understand which file he's talking about, just use
http://jqueryui.com/latest/ui/ui.core.js and
http://jqueryui.com/latest/ui/ui.slider.js
instead of the custom jquery ui, and scroll to line 360 of
ui.slider.js to find the "allowed" variable".

reply

Andrea
07/15/2009 - 08:14

Hi to all and thanks for the cool code!!!
I have this problem: http://89.186.66.71/dmanagement_ok/html/scroll/multimediaw.asp?mnome=megan

Anyone help me?

thanks

Bye

reply

The Fattest
07/15/2009 - 12:52

What is the issue, from a quick glance I didn't see anything obvious.

reply

invisionblue
07/27/2009 - 22:23

http://www.invisionblue.com/lab/scrollhorizontal/slider_test.html how come when I click the orange scroller it moves about 30-40 pixels to the right?

reply

The Fattest
07/28/2009 - 09:10

This is happening because the click is being recorded on the scroller (track) and the middle of the slider button is the 0 point on it, the left side of the button is. Not sure the best way to remedy that, will try and think up something though.

reply

invisionblue
07/28/2009 - 10:15

If I made the button smaller would that help? I've noticed on yours and some others it's thin and doesn't do that.

reply

The Fattest
07/28/2009 - 12:37

Yeah that would certainly help.

reply

invisionblue
07/28/2009 - 13:33

problem solved without changing the size. I simply removed the attribute "width: 66px;" and made it "padding: 5px 33px 5px 33px;" and it now works smoothly. So I suppose the width attribute was the problem here.

reply

Ian
08/04/2009 - 13:25

great work! I'm having a problem with using a background image on the handle. If I use a root-relative url, or a full url, it creates all kinds of problems in IE. Something like this doesn't work:

.ui-slider-handle{
background:url(http:www.foo.com/scrollbar/handle.gif);
}

but this works:
.ui-slider-handle{
background:url(scrollbar/handle.gif);
}

I need to use root-relative links in my site, but can't figure out why this is causing problems.

reply

The Reddest
08/04/2009 - 15:14

At first glance, the URL syntax is incorrect. You have:

http:www...

Where it should be

http://www...

You forgot the set of slashes after the http.

reply

Ian
08/04/2009 - 15:31

Sorry, that was just a typo in my comment. The problem persists with a properly formed url. The problem involves quirky behavior during hover and drag states in IE. I tried making explicit styles for different link states (.ui-slider-handle:hover, ect), as well as the specific class names that are added when the handle changes states (ui-state-hover, ui-state-focus).

reply

The Fattest
08/04/2009 - 17:13

Which version of IE are you using?

reply

Ian
08/05/2009 - 12:39

IE6

reply

The Reddest
08/04/2009 - 17:15

I always put the contents of url() in quotes. ex url("scrollbar/handle.gif"). Does that help at all?

reply

Ian
08/05/2009 - 12:40

the behavior is the same for single quotes, double quotes, and no quotes

reply

Ian
08/05/2009 - 15:57

If you want a wide scrollbar you'll run into a couple issues, but I've found solutions.

If the scrollbar is wide it will align to the right of the mouse when you click the track, rather than ending on the center. This can be fixed by adding a right-margin to the handle that is the negative value of half the handle width. Example:

.ui-slider-handle {
width: 92px;
height: 12px;
position: absolute;
margin-left:-46px;
overflow:hidden;
}

The handle also hangs off either end of the track rather than ending at the end of the track like you would expect from a normal scrollbar. Fix this by subtracting the handle length from the track width and adding a margin to the left and right of the track equal to half the length of the handle.

To make the shortened track appear longer you'll need to add elements to either side matching the track background, or use a single element on a lower z-index below the track.

The make the left and right sides of the track go to the end, you can add buttons on a higher z-index above the slider. Here'
s an example:

css:
[css]
#sliderLeftButton{
           position:relative;
           top:-36px;
           height:12px;
           width:56px;
           overflow:hidden;
}
#sliderRightButton{
           position:relative;
           top:-48px;
           left:912px;
           height:12px;
           width:56px;
           overflow:hidden;
}

html:

<div id="sliderLeftButton">
                <div style="height:12px; width:56px; display:block"  onClick="javascript:moveSlider(0);"></div>
      </div>
      <div id="sliderRightButton">
                <div style="height:12px; width:56px; display:block" onClick="javascript:moveSlider(100);"></div>
</div>

javascript:

function moveSlider(value){
        $('#content-slider').slider( 'value' , value );
}

This code isn't optimized, you can probably clean up the css some. I hope this was helpful.

reply

wegg
08/17/2010 - 08:40

this is amazing, but I am a Noob,

where do i put the HTML tags? anywhere, or somewhere in the earlier tags?

reply

jd17ortiz
08/05/2009 - 17:48

Good evening friends

First, i want to congratulate you for the great job you're doing.

I've been having some troubles trying to put together the solution by increase the 8px size of ui-slider-handle to 40px. It actually increase but after move the slider to the end of the area it just fade away. Is there any solution for this problem? Thank you a lot for all your time, please let me know if you need extra information. I will appreciate so much your help, i don't know what else to do, i'm kind of desperate. Thank you friends. Best Wishes

reply

The Fattest
08/05/2009 - 19:26

One of the earlier comments had an issue similar, he solved this by keeping the standard width and adding padding the slider to make it bigger.

reply

sam
03/05/2010 - 00:43

the fattest, could you help me out with the width of the content holder. I need to find a way to not define it in the css bc I wont know how many items ill have scrolling horizontally. all items are the same width and height. please help! thanks

reply

jd17ortiz
08/06/2009 - 08:51

Hello My friend,

The fattest, I actually did read the post from invisionblue but in my case it didn't work that solution 'cause setting the padding the size of the ui-slider-handle did increase but it keeps getting out of the boundaries at the end of the area. Thank you a lot my pal,. I really appreciate all the time you're putting on this! Best wishes

The next link: http://jd17ortiz.100free.com/slider_test.html has an example of what im trying to do, in the code i change the padding as the last comentary says but the slider keeps getting out of position

JD

reply

The Fattest
08/12/2009 - 17:42

JD, sorry for late response but I was out for town for some RL vacation. I figured out why it goes out of bounds, they use the css left attribute to move it and they used to use absolute px placement calculating the correct amount for the width of the slider bar. They no longer do that and use percentages % now. This causes the slider handle to go off the end. They center the handle by using negative margin on the handle. I personally don't like this solution at all, but that is the way it is. I would suggest if you want to scroll the entire distance inside the bar you wrap the scroll bar in another div, in which you style like your scroll bar and then inside offset the actual scroll bar by the width of your handle. Let me know if this doesn't work out or if you need an example of what I am talking about.

reply

jd17ortiz
08/17/2009 - 15:16

Thank you the fattest, you don't have to apologize, i understand perfectly. About the slider topic, i understand what you're suggesting, but it isn't clear enough for me the use of an internal div, if you could show me an example about it i would appreciate a lot. The solution a have come througth is the one you suggest about center the handle but this makes the sensible area of the scroll shrinks, but i don't think is quality at all.
My friend, if it isn't too much bother i would like to know if in order to implement two sliders i have to use the function $("#content-slider").slider({ twice, changing the id of each div for the slider. It isn't any other more elegant solution?
Thank you for everything and sorry for all the trouble. Greetings

JD.

reply

pradeep
11/11/2009 - 07:28

hi, can you pls give us an example to stop the slider going out of bound at the end. I have been struggling to solve this issue.

reply

Rajesh
09/04/2009 - 03:23

hi dud,
it really nice, but I cant able to use #content-scroll's width by %, because whole pages i m making with % only, if I give width by (px)It does not flow of design page. Please help.

reply

Rajesh
09/04/2009 - 05:25

Hey it working........ thk alot

reply

Anonymous
09/01/2011 - 22:24

Hi, i wonder how did you handle the percentage width issue? Could you please teach it also to me. I need to use percentage width but if i do, the content-scroll width goes of the page when i place too many data. thanks

reply

jenningsk
09/15/2009 - 15:23

Awesome, this really helped me out with something Ive been working on but I was hoping for help getting things to scroll vertically.

I changed orientation to vertical, and made the appropriate CSS changes butt the scroll bar wont work.

do I have to make changes to handleSliderChange and handleSliderSlide?

I changed the lines for max scroll values to:

var maxScroll = $(".content-scroll").attr("scrollHeight") - $(".content-scroll").height();

but do I have to change that "scrollLeft" on the next line too?

reply

brainac
09/23/2009 - 10:29

I've got few questions about that awsome slider.

1. Is it hard to make it slowly move itself? I'm new with jQuery and even if it's piece of cake I won't figure it out myself.

2. Is it possible to catch mouse wheel moves over it, and scroll it accordingly?

Thank you for any help

reply

Anonymous
09/23/2009 - 16:50

i'm sorry if this is double post or i missed it in description, but for me, it looks better if the speed of sliding content is calculated in same way and using same easing as slider animation when clicking on slider tray. Speed of animation is calculated by the distance of mouseclick from the handle.
However its very nice example.

sry for poor english.

reply

Jabie
10/08/2009 - 19:14

I am trying to do vertical scrolling too and I got the scroll to work except that the slider doesn't move/slide.

I changed the follow:

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

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

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

Any idea how to make the slider handle to move? Thx a lot.

reply

POPOEVER
11/14/2009 - 04:22

@Jabie you need a initiate value below orientation option I think, say:

orientation: 'vertical',
value: 100,

reply

Kevin "Tentonaxe"
01/07/2010 - 11:48

This does cause the thumb to appear at the top of the scrollbar, however, the scrolling is inverted(the top of the scrollbar shows the bottom of the content)

To fix this, change the functions so they look like this:

$("#artist_bio_slider").slider({
  animate: true,
  change: handleBioSliderChange,
  slide: handleBioSliderSlide,
  orientation: 'vertical',
  value: 100
});
function handleBioSliderChange(e, ui)
{  
  var maxScroll = $("#artist_bio_content").attr("scrollHeight") - $("#artist_bio_content").height();
  $("#artist_bio_content").animate({scrollTop: (100-ui.value) * (maxScroll / 100) }, 1000);
}
function handleBioSliderSlide(e, ui)
{
  var maxScroll = $("#artist_bio_content").attr("scrollHeight") - $("#artist_bio_content").height();
  $("#artist_bio_content").attr({scrollTop: (100-ui.value) * (maxScroll / 100) });
}

the only difference is
ui.value
became
(100-ui.value)

reply

Robin
01/22/2010 - 21:51

Kevin, I've found this tutorial and tried to adapt it to a vertical slider bar. I saw your comment and followed it, but my slider still doesn't slide. The content scrolls, but the slider doesn't move. Here's my code, do you see what could be the problem?

 

$("#content-slider").slider({
    animate: true,
    change: handleSliderChange,
    slide: handleSliderSlide,
    orientation: 'vertical',
    value: 100
  });
});

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

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

reply

Rashmi
02/02/2010 - 03:49

I also used this code , but the slider does not moves. Any workaround ?

reply

Anonymous
02/14/2010 - 15:09

To get the slider to move using a vertical bar you need to change the css form

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

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

change the position from a fixed top to fixed left.

reply

JSD
12/03/2009 - 09:53

Anyone else having issues with skinning the handle in ui 1.7.2

for what ever reason it seems to be defaulting back to the stock handle and not allowing me to use my own skin for it.. :/

1.7.1 works fine, I would go back to 1.7.1 but I already am using 1.7.2 through out the site and I would like to stay up to date..

reply

Kevin "Tentonaxe"
01/07/2010 - 13:58

I didn't have any trouble skinning my thumb, make sure that your custom CSS comes after jquery ui's themebuilder so that your styles overwrite its styles.

reply

dennis78
12/09/2009 - 10:51

Hi, when i use the script it works fine, but when i click the slider handle there appears a little blue halo around it... anyone knows how to get rid of this?

Thanks

reply

bjorntheart
01/08/2010 - 05:29

Hi there

My mouse moves off my slider as I scroll. The issue resulting from this is that my content don't scroll all the way

I've also modified my #content-slider and .ui-slider-handle a bit according to my needs

#content-slider
{
    width: 100%;
    background: #BBBBBB;
    position: relative;
}

.ui-slider-handle
{
    width: 2px;
        height: 40px;
        position: absolute;
        top: -4px;
        background: #ff0000;
        background-image:none;
}

reply

nettencicek
02/07/2010 - 16:24

good thakns

reply

Ajax Coder
02/10/2010 - 06:28

Thanks for these useful JQuery slider tips.

Don't overlook the ASP.NET Ajax slider, it can easily be swapped with JQuery slider and can make it easier and solve some common issues:

http://www.timacheson.com/Blog/2010/feb/ms_ajax_slider

reply

Anonymous
03/05/2010 - 19:21

Is there any way to get the slider to move to a set point on page load. The idea being when something is clicked in the slider and page reloads I can move the slider along so the item they clicked is showing on the left.

reply

Anonymous
03/22/2010 - 10:45

I Love it! Thank you! However, I have a mootools slideshow on the page I want to add this to and they will not work together. Do you know how I would use a NoConflict script to make them both work on 1 page?
Thanks!

reply

gerrycircus
04/06/2010 - 20:10

Awesome slider...

BUT...

When i download the .zip and open it in FF, there's an issue with the handle overlapping the div "content-holder". The distance is equal to the width of the handle.

The example on your site works PERFECTLY - but the demo .zip has the error in it.

Any ideas?

reply

Flex
07/28/2010 - 03:46

Hi Gerry.

Were you able to fix this? If so, can you please post the solution here? If not, can anyone help us? :D

Thanks!

reply

aletsix
04/10/2010 - 18:36

Very useful script, absolutely love it!

Just quoting one question posted before(anonymous 03/05/2010 - 19:21) which I think would be a nice feature to have: is there any way to change the starting point of the slider so that the handle and clicked scrolled item are in the middle when a new page loads?

reply

Anonymous
05/17/2010 - 16:17

hmm, tried out the example scroller above and it did not function at all (tried in Firefox 3.6.3 and Internet Explorer 7). Any idea why this isn't working for me? I certainly don't have Javascript turned off!

reply

The Fattest
05/17/2010 - 16:35

Sorry about that, I had made a change to the site recently which apparently causes our jQuery tutorials to stop working. This should be fixed. Thanks for letting us know.

reply

nerdess
06/03/2010 - 08:31

hey all

i've rewritten the whole thing to make the scrolling vertical...i've also wrapped it as a jQuery plugin so it can be easily evoked on multiple elements like e.g.:

$('div.slider-vertical').sliderVertical({height:100, width: 200});

<div class="slider-vertical">
    <div style="position:relative;">
Lorem ipsum dolor sit amet....
    </div>
</div>

the js code for the sliderVertical plugin is below.

However, the whole slider thingy doesn't work in IE 7 (not sure about the other IE versions just tested in IE 7 for now) when there are relative positioned elements inside the slider-vertical div...?!?

thanks
sissi

(function($){

   var SliderVertical = function(element, o)
   {
       element = $(element);
       var obj = this;
       var s = $.extend({
          element: $(element),
          height: 300,
          width: 100, //needed if element is initially display:none
          heightContent: '',
          elSlider: '',
          elScroll: '',
          elHolder: ''
       }, o || {});

       //init
       this.init = function() {

        //getting height of element even if it's hidden initially
        $(element).clone().attr('id', 'sliderTempXXX').css({'position': 'absolute', 'top': 0, 'width': s.width, 'visibility': 'hidden'}).appendTo('body');
        s.heightContent = $('#sliderTempXXX').height();
        $('#sliderTempXXX').remove();

        //alert(s.heightContent + 'xxx' + s.height);

        if (s.heightContent > s.height) {

            $(element).append('<div class="content-slider">content slider</div>')
            .wrapInner('<div class="content-holder">')
            .wrapInner('<div class="content-scroll">');

            $(element).height(s.height).css({'padding-right': '22px', 'position': 'relative'})
            s.elSlider = $(element).find('.content-slider').height(s.height).css({'position': 'absolute', 'right':'2px', 'top':0, 'text-indent':'-9999px'});
            s.elScroll = $(element).find('.content-scroll').height(s.height).css({'overflow': 'hidden'});
            s.elHolder = $(element).find('.content-holder').height(s.heightContent);

            //alert($(element).html());

            function handleSliderChange(e, ui)
            {
              var maxScroll = $(s.elScroll).attr("scrollHeight") - $(s.elScroll).height();
              $(s.elScroll).animate({scrollTop:
              (100-ui.value) * (maxScroll / 100) }, 1000);
            }

            function handleSliderSlide(e, ui)
            {
              var maxScroll = $(s.elScroll).attr("scrollHeight") - $(s.elScroll).height();

              $(s.elScroll).attr({scrollTop:
              (100-ui.value) * (maxScroll / 100) });
            }

            $(s.elSlider).slider({
                animate: true,
                change: handleSliderChange,
                slide: handleSliderSlide,
                orientation: 'vertical',
                value: 100
            });
        }

       }

   };

  $.fn.sliderVertical = function(o)
   {
       return this.each(function()
       {

           var element = $(this);

           // Return early if this element already has a plugin instance
           if (element.data('sliderVertical')) return;

           // pass options to plugin constructor
           var sliderVertical = new SliderVertical(this, o);
           sliderVertical.init();

           // Store plugin object in this element's data
           element.data('sliderVertical', sliderVertical);


       });
   };
})(jQuery);

reply

Anonymous
06/06/2010 - 00:50

Hi to all and thanks for the great code. I have one problem and can't fix it. The slider dosn't work when I use it with an ipad or iphone. Have you got an idea how to fix it?

reply

Anonymous
03/21/2011 - 13:28

it works if you click on the bar and not try to drag it.

reply

Rodre
07/14/2010 - 18:04

First thank you for the code.

Is there any way to get the div scrolling whith mouse wheel also? I mean both the slider and the mouse wheel being oprable.

Rodre

reply

George T.
07/18/2010 - 11:04

Hi,

Is there a way to add two extra buttons for back/next?
Thank you.

reply

The Fattest
07/19/2010 - 11:40

Yeah sure, I think am going to work up a updated tutorial with some additional features like this. I will let everyone know when this is done.

reply

kasunshashi
08/02/2010 - 03:58

Great, I'm really looking forward to have this feature soon.

reply

kasunshashi
08/02/2010 - 03:53

Thanks a lot for great tut. One thing.....

How can I load the selected panel (not the first panel) at the load. I mean I want to start from second panel when loading for fist time. and the slider also should be at appropriate position.

Thanks in advance for any help and really sorry if I had asked a stupid question.

reply

cnanney
08/20/2010 - 22:23

Great tutorial, this was a nice start for what I needed. I didn't want to have to alter the jQueryUI source to have a smooth scrolling div when clicking on the slider bar, so here's the modification I made:

var type;

$(".type-cat-slider").slider({
    animate: true,
    start: checkType,
    slide: doSlide,
    max: 750
});

function checkType(e){
    type = $(e.originalEvent.target).hasClass("ui-slider-handle") ? 'drag' : 'click';
}

function doSlide(e, ui){
    var parent = $(e.target).prev(".type-cat-scroll"),
    maxScroll = parent.attr("scrollWidth") - parent.width();

    if (type == 'drag')
        $(e.target).prev(".type-cat-scroll").attr({scrollLeft: ui.value * (maxScroll / 750) });
    else
        $(e.target).prev(".type-cat-scroll").animate({scrollLeft: ui.value * (maxScroll / 750) }, 400);

}

I use the 'start' event to determine whether the handle was clicked or not, which tells you if it's a handle drag or a click. Then, in the slide handler I specify whether to animate the scroll based on which type it is.

Also with using '$(e.target).prev(".type-cat-scroll")' I can use this code on multiple sliders on the page without needing them to have unique IDs.

Example of the code correctly handling clicks vs. drags:
http://i.imgur.com/Uks6O.gif

Thanks again!

#### EDIT ####

Adjusted code to fix a cross-browser problem. This solution works properly in IE, FF, Chrome, Opera and Safari.

reply

levilarsen
11/03/2010 - 15:36

I'm having some trouble getting your code to work for me. The content doesn't scroll.

I'm using:
jquery-1.4.2.min.js
jquery-ui-1.8.6.custom.min.js

Code:

$(document).ready(function(){
var type;

$(".type-cat-slider").slider({
    animate: true,
    start: checkType,
    slide: doSlide,
    max: 750
});
});

function checkType(e){
    type = $(e.originalEvent.target).hasClass("ui-slider-handle") ? 'drag' : 'click';
}

function doSlide(e, ui){
    var parent = $(e.target).prev(".type-cat-scroll"),
    maxScroll = parent.attr("scrollWidth") - parent.width();

    if (type == 'drag')
        $(e.target).prev(".type-cat-scroll").attr({scrollLeft: ui.value * (maxScroll / 750) });
    else
        $(e.target).prev(".type-cat-scroll").animate({scrollLeft: ui.value * (maxScroll / 750) }, 400);

}

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="jquery-1.4.2.min.js" language="javascript" type="text/javascript"></script>
  <script src="jquery-ui-1.8.6.custom.min.js" language="javascript" type="text/javascript"></script>
  <script src="slider_test.js" language="javascript" type="text/javascript"></script>
  <style>
    #main {
      width: 510px;
      margin: 0 auto;
    }

    .type-cat-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;
    }

    .type-cat-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;
  }
  </style>
</head>
<body>
<div class="type-cat-slider"></div>
<div class="type-cat-scroll">
  <div id="content-holder">
    <div class="content-item">
      <p>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.</p>
      <p>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.</p>
    </div>
    <div class="content-item">
      <p>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.</p>
      <p>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.</p>
    </div>
    <div class="content-item">
      <p>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.</p>
      <p>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.</p>
    </div>
    <div class="content-item">
      <p>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.</p>
      <p>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.</p>
    </div>
    <div class="content-item">
      <p>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.</p>
      <p>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.</p>
    </div>
  </div>
</div>
</body>
</html>

reply

cnanney
11/03/2010 - 18:38

@levilarsen

Yeah, I did a poor job of explaining how the code expects the HTML to be laid out a certain way, especially all those $(e.target).prev()'s. The doSlide function in my example is pretty useless without some accompanying HTML. I think I'll write up a sample demo page and post the URL here, but for now if you email me (cnanney at gmail) I can send you to a working example to examine.

reply

henry
01/20/2011 - 10:23

can you email me your working example?

zhlu@umich.edu

thanks!

reply

Bob C
01/13/2011 - 11:30

Thanks for the tutorial, very useful. I got this working fine however I get an annoying light blue box around the slider handle when I select it, which is odd because this does not appear on the example on this page. Is there a simple option to deactivate this ?

reply

The Fattest
01/13/2011 - 13:31

My guess is that is the focus css style for the element. Try something like, replacing element with your handle of course:

element:focus {
  border: 0;
}

reply

Bryan
01/29/2011 - 08:38

This is a great tutorial, but I do have one question. How do I increase the width of the scroll handle without causing it to move when you click on it? If I increase to 100px, and I click on it past the original 8px, the content slides without moving the scroll bar.

reply

Piscean King
01/29/2011 - 15:52

Love the script.

How can I use multiple instances of this scroller on same page?

Appreciate the help.

reply

Xander Gerrmann
02/02/2011 - 15:42

Hello,

I was wondering if it is possible to scroll from right to left instead from left to right. The reason for this is that I want the feel of a timeline. But when you load the page the most recent things must be showed (start the handle at the right). How can I achieve this without reversing the content?

thanks in advance

reply

The Fattest
02/04/2011 - 11:35

This shouldn't be hard to do, just on load set the content scroll to the max scroll and set your handle at 100% then you'll be able to simply draw the handle to the left to scroll.

reply

Xander Gerrmann
02/05/2011 - 06:30

I'm quite a noob with this code:P
This is the code that I have downloaded.:

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

});
});

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) });
}

------------------------------------
What should it look like to get the result I want?

reply

Xander Gerrmann
02/08/2011 - 10:35

Ok, my handle is now at 100% (value: 100),
but how to get the showed content start on the right side when the page is loaded? So that the handle corresponds tot the showed content?

reply

cnanney
02/05/2011 - 20:36

As a follow-up to my comment about having this functionality without having to update the jQueryUI source, here is a post explaining my solution:

http://bit.ly/gAgvdk

reply

CodaSliderer
02/16/2011 - 02:07

Is this scrollbar compatible with Coda-Slider 2.0 (http://www.ndoherty.biz/demos/coda-slider/2.0/) ???!!!

reply

Kinky
03/14/2011 - 09:51

Hi there,

i would like to know, like others before, how not to have set the width of the container div (content-holder)
Amy wrote:
What I did was calculate the amount of child divs in the content holder. Then, since I knew the width of each content-item div i set $(”#content-holder”).css(”width”, childWidth * amountOfChildren

Could anybody tell me where and how to implement it?

Thanks

reply

Neo
03/15/2011 - 22:13

If it is possible to make the scroll handle starts at the center, together with the content centered..

Can you help me do that. I'm a newbie in javascript.

Thanks in advance.

reply

Xander Gerrmann
03/16/2011 - 13:09

I am also curious for the solution.

reply

madrazo2010
03/23/2011 - 06:30

Hi I've adapted code to this helpfull jquery slider, but I have a problem. When I scroll many times with a left or right button one image in scroll bar disappears.
I try to changed speed scroll, but the problem remain. I used another jquery file called jQuery Rawr zoom v1.0 - http://hungred.com/2009/04/07/javascript-framework-jquery/tutorial-jquery-effect-zoom/ to zoom images in slider.
Later I put link to a test page to see that I try to explain here.

var speed = 800  //800
var delay = 2000    //2000
var size = 210 + 5 //210 + 5
var links, boxs, pointer, last, pic, numImgs, positions, i, with, n, step, stop

$(window).load(function(){
  // next
  $("#content_holder").find("span").append("<div class='content_item'><a class='content_item_l' href=''><img src='' height='140px' border='0'></a></div>")
  // previous
  $("#content_holder").find("span").append("<div class='content_item'><a class='content_item_l' href=''><img src='' height='140px' border='0'></a></div>")

  pic = $("#content_holder").find("img")
  numImgs = pic.length - 2 // pic[numImgs] save the next one and  pic[numImgs + 1] the previous one
  links = $("#content_holder").find("a")

  boxs = $("#content_holder").find(".content_item")

  $(pic[numImgs])[0].src = $(pic[0])[0].src
  $(pic[numImgs + 1])[0].src = $(pic[numImgs - 1])[0].src
  $(links[numImgs])[0].href = $(links[0])[0].href
  $(links[numImgs + 1])[0].href = $(links[numImgs - 1])[0].href

  positions = new Array(numImgs);
  for (i = 0; i < numImgs; i++) {
    with = 0
    for (n = 0; n < i; n++) {
      with += size
    }
    positions[i] = with
    $(boxs[i]).css("left", with)
  }
  positions[numImgs] = positions[numImgs - 1] + size
  $(boxs[numImgs]).css("left", positions[numImgs])

  positions[numImgs + 1] = -size
  $(boxs[numImgs + 1]).css("left", positions[numImgs + 1])

  pointer = 0

 
})

function change(d) {
  while (stop) {
     
  }
 
  d ? moveRight() : moveLeft()
 
}

function moveLeft() {  
  stop = 1
  // move the visible ones
  i = pointer
  do {
    positions[i] -= size
    $(boxs[i]).animate({left: positions[i]}, speed)
    i = (i + 1) % numImgs
  } while (i != pointer)

  // move the next one
  positions[numImgs] -= size
  $(boxs[numImgs]).animate({left: positions[numImgs]}, speed, function() {
    // and change the image
    $(pic[numImgs])[0].src = $(pic[pointer])[0].src
    $(links[numImgs])[0].href = $(links[pointer])[0].href
    positions[numImgs] = with + size
    $(boxs[numImgs]).animate({left: positions[numImgs]}, 0)
  })

  // the firts one becames the last one
  positions[pointer] = with
  $(boxs[pointer]).animate({left: positions[i]}, 0)

  // to change the previous one
  $(pic[numImgs + 1])[0].src = $(pic[pointer])[0].src
  $(links[numImgs + 1])[0].href = $(links[pointer])[0].href
  positions[numImgs + 1] = -size
  $(boxs[numImgs + 1]).animate({left: positions[numImgs + 1]}, 0)

  // to move the pointer
  pointer = (pointer + 1) % numImgs
  stop = 0
}

function moveRight() {
  stop = 1
  last = pointer ? pointer - 1 : numImgs - 1
  // to move the previous
  positions[numImgs + 1] = 0
  $(boxs[numImgs + 1]).animate({left: positions[numImgs + 1]}, speed)

  //  to move the visible ones
  i = pointer
  do {
    positions[i] += size
    $(boxs[i]).animate({left: positions[i]}, speed)
    i = (i + 1) % numImgs
  } while (i != pointer)

  // to change the previous image
  $(pic[numImgs + 1])[0].src = $(pic[last])[0].src
  $(links[numImgs + 1])[0].href = $(links[last])[0].href
  positions[numImgs + 1] = -size
  $(boxs[numImgs + 1]).animate({left: positions[numImgs + 1]}, 0, function() {
    // la que era última pasa a ser primera
    positions[last] = 0
    $(boxs[last]).animate({left: positions[last]}, 0)
  })

  // to change the next one
  $(pic[numImgs])[0].src = $(pic[last])[0].src
  $(links[numImgs])[0].href = $(links[last])[0].href
  positions[numImgs] = with + size
  $(boxs[numImgs]).animate({left: positions[numImgs]}, 0)

  // and move the pointer
  pointer = last
  stop = 0
}

reply

riffbird
03/27/2011 - 10:11

nice collection of jquery slideshow.
Thanks to sharing.

reply

SerNeo
03/29/2011 - 14:15

Hi,
I have noticed the bug in IE9:
- the scrollpane doesn't move when you click on it and try to move.

Any ideas how to fixit it?

reply

Anonymous
04/01/2011 - 02:04

Hi,

I have a problem. I have written some javascript to display the item of dropdown on dropdownclick in content-item div. But When I am clicking on this dropdown to show the items slider handle is disappering. Its again appearing only on page refresh. Is there any workaround for this?

Thanks in advance.

reply

Ricardo
04/20/2011 - 10:35

hola hay alguna manera para pueda deslizar el contenido, utilizando la rueda de scroll del mouse?...thanks

reply

Ricardo
04/20/2011 - 10:36

hi there a way to slide down the content, using the mouse scroll wheel? ... thanks

reply

Anonymous
04/21/2011 - 07:39

Yeah, I have spotted the bug in IE9 too, bummer

reply

Hernan
04/22/2011 - 10:38

I'm using dynamic image sizes with these few lines.

var t = 0;
    $('#content-holder .content-item').each(function() {
        t += $(this).outerWidth(true);
    $('#content-holder').css('width', t + 20);

reply

Tony O
05/20/2011 - 12:02

I noticed the bug in ie9 with ui 1.7.2. The change event of the slider gets called when you click on the slider and try to drag it, instead of when you let go. Looks like upgrading to the latest version 1.8.13 fixes this. I saw bug issue that had a fix for this problem in the ui.slider.js component. So they probably fixed it now in the latest jquery UI 1.8.13.

reply

Anonymous
06/09/2011 - 08:58

it does'nt worked in codeigniter

reply

Eva J.
06/14/2011 - 10:36

Finally I got this to work the way I want; then I started testing in IE9... :(

Anyone any idea how to fix this? I am not the most technical person though ;)

reply

Eva J.
06/14/2011 - 10:46

Still can't believe I got this to work.. but I did.

Just replace the ui-1.7.1.custom.min.js with the latest version 1.8.13 (download it here; http://jqueryui.com/download)

Of course, change your index.html and there you go.

The only thing I found: If click on the scrollbar in IE9, your cursor moves a bit to the left. It still works but it's better to fix this. Has anyone an idea?

reply

Anonymous
06/20/2011 - 11:37

Hey,

the slider handle is not draggable on IE9.
is there fixes for it?

reply

Anonymous
09/06/2011 - 17:12

I need the answer too.

reply

Rod
11/06/2011 - 21:03

Try inserting the tag:

reply

Rod
11/06/2011 - 21:06

 <meta http-equiv="X-UA-Compatible" content="IE=8" >

reply

nabin
07/13/2011 - 04:57

thanks a lot for the script

reply

CJ
07/20/2011 - 07:52

Hi,

What's the best way for me to increase the size of the slide_handle without it sliding off the end of the track?

Regards

Craig

reply

Sha
08/05/2011 - 10:13

I really enjoy this slider and it worked for a design that I created for my personal site. I am having a problem with using the slider that has images and trying to load the images using fancybox. If I remover the jQuery JavaScript Library v1.3.2 from my page fancybox works fine, but then of course the slider does not work. Does anyone have any solution to fix this problem? I do not know that much jquery nor javascript and any input would be great!

Thanks, Sha.

reply

deep
08/09/2011 - 14:44

hi
This is a very nice script, thanks for sharing with us.
Is it possible to show this slider only when needed meaning when the content does not fit in the browser window

thanks

reply

Vladster
08/09/2011 - 19:12

To also allow manual move / toggle to automatic:

jQuery(document).ready(function() {
if ( jQuery('#slider-progress').length ) {
                jQuery("#slider-progress").slider({
                        animate: "slow",
                        change: handleSliderChange,
                        slide: handleSliderSlide
                });
                prev_inc = 0;
                pauseTime = 2000;
                setTimeout ( "scrollSliderToRight( "+ pauseTime +", 1)", pauseTime );
        }
});

manualMove = 0;
function scrollSliderToRight( pauseTime, inc ) {
        if ( inc > prev_inc && inc < 11 && manualMove == 0 ) {
                prev_inc = inc;
                jQuery("#slider-progress").slider("value", 10*inc);
                inc+=1;
                setTimeout ( "scrollSliderToRight("+pauseTime+", "+inc+")", pauseTime );
        }
        else {
                if ( inc > prev_inc )
                        inc-=1;
        }
        if ( inc <= prev_inc && inc >= 0 && manualMove == 0 ) {
                prev_inc = inc;
                jQuery("#slider-progress").slider("value", 10*inc);
                inc-=1;
                setTimeout ( "scrollSliderToRight("+pauseTime+", "+inc+")", pauseTime );
        } else {
                if ( inc <= prev_inc ) {
                        setTimeout ( "scrollSliderToRight("+pauseTime+", 1)", pauseTime );
                }
        }
}

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

function handleSliderSlide(e, ui) {
        manualMove = 1;
        var maxScroll = jQuery("#slider").attr("scrollWidth") - jQuery("#slider").width();
        jQuery("#slider").scrollLeft(ui.value * (maxScroll / 100));
}

This works with jQuery 1.4.4 and UI 1.8.0.
Unfortunately I haven't updated it to work with the latest jQuery, because I don't know why it doesn't.
Something in the code? If anyone knows, please share.

reply

Kerry
08/22/2011 - 01:32

Hi

I have just implemented your scroll bar into a website that I am building but I have got two issues.
1. when you click on the sllider to drag it, it shows a blue border. I have no border applied and don't know where this is happening to turn it off.

2. is it possible to still use the mouse to scroll as well as the slider?

 #content-slider {
     width: 100%;
     cursor:pointer;
    height:1px;
   border-top:1px dashed #b3b3b3;
      position: relative;
 margin-top: 25px;
    }

    .ui-slider-handle {
    position:absolute;
        background-color:#fff;
        height:20px;
        width:80px;
        top:-12px;
        display:block;
        cursor:move;
        border: 0px;
        background-image:url(../images/move_me.gif)
    }
       
         .ui-slider-handle:active {
        border: 0px;
        background:#fff;
        background-image:url(../images/move_me.gif)
        }
       

    #content-scroll {
      width: 100%;
      height: 600px;
      overflow: hidden;
    }

    #content-holder {
      width: 9660px;
      height: 600px;
    }

    .content-item {
      width: 290px;
      height: 600px;
      padding: 5px;
      float: left;
  }
 
  #content-holder ul li {
        display: inline;
        height:600px;
        white-space: nowrap;
}

The website that i am working on is below

http://www.redrobyndesign.com/kerry/brand.htm

reply

adel aboelwafa
08/27/2011 - 05:22

#main{
min-height:500px;

}

reply

Anonymous
08/28/2011 - 15:34

Does this work with photos and can you replace the slider graphic with something fancy - and if so, where and how? Thanks!

reply

wafa
08/31/2011 - 05:28

if(isset)

reply

no4spam
09/09/2011 - 07:47

I got the slide work well and here is link http://www.tommycarl.com/justAnIdeaLinda/

The only issue I have is the slider will not slide on the iPad

reply

Anonymous
09/12/2011 - 13:55

Is there a way to position the starting point of the slider when a button is clicked?

reply

Chetaru
09/15/2011 - 06:58

Hi..
Thanks for sharing this information and resources it's really help full for me with the help of this we can improve our designs and development I really inspire with this information thanks

reply

toppel
09/26/2011 - 04:43

Nice Howto, but it does not work with jquery-1.6.2
Is ther another howto ?

reply

anonymous
09/27/2011 - 00:17

hii,
i am using this slider twise in jQuery tabs but only one at a time works can u please help me

reply

getinfo
10/03/2011 - 12:17

Try to add to gridview results but the slider button will not show. Any one else had this issue.

reply

AreA
10/14/2011 - 11:55

Hi,
Is there anyway to make this scrollbar auto sliding?

reply

Kees Schepers
10/25/2011 - 15:01

I fixed the example in this tutorial with new JQuery and JQuery-UI libraries and made a GitHub project:

https://github.com/keesschepers/jquery-ui-content-slider

If anyone has improvements please fork it :)

Example: http://keesschepers.nl/jquery-ui-content-slider/

reply

Sérgio Almeida
10/28/2011 - 05:38

That is quite cool, I was looking for something like this (since I'm a noob at jquery). Thanks!

However, the animation is not smooth, it's actually quite buggy.
Also, when I change the width of the slider's handle to 100px, it behaves strangely. The handler even comes out of the slider to the right.
If you can fix this, I'm actually quite curious to see the solution, since I still have a lot to learn.
Keep up the good work, mate!

reply

Sajith
12/08/2011 - 06:59

Hi Sérgio,

The handler even comes out of the slider to the right. - Did u able to fix this ?

reply

Dave
10/26/2011 - 06:27

A slider that works on iPhone and iPad.
http://blog.egorkhmelev.com/2010/03/jquery-slider-update/

reply

Anonymous
11/02/2011 - 20:47

can i use it with the height?

reply

Guillaume
11/27/2011 - 17:47

Tested with new jQuery 1.7 and this example seems not working anymore. Will try to make it working tomorrow, but if the admin can glance at this before... :)

reply

Vitor Neves
11/28/2011 - 10:23

Hi there
I was trying to apply your script to a website and worked fine, but now i have a problem. I'm using images that will be loaded from db and their height will be fixed but their width will be variable.
It is possible to make it work this way?
I tryed to change the css but stop working

Regards

Vitor Neves

reply

icdbox.com
11/30/2011 - 21:12

Thanks

reply

Anonymous
12/28/2011 - 06:30

i cannot get the ui slider handle to appear, and the divs won't display horizontally, only vertically. I downloaded the example code and it was the same issue... any help?

reply

Ronald van Meer
12/30/2011 - 10:55

I've got it working with jQuery 1.7.1
I am using the following code:

var nr_Pictures = 4;
        var width_Picture = 618;

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

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

i have replaced $("#content-scroll").attr("scrollWidth")
with width_Picture * nr_Pictures which represents the total length of the DIV.

please take note! the pictures all have the same size,
if this does not apply for you, create your own javascript logic and replace
(width_Picture * nr_Pictures) with your own calculated width.

reply

Add Comment

Put code snippets inside language tags:
[language] [/language]

Examples:
[javascript] [/javascript]
[actionscript] [/actionscript]
[csharp] [/csharp]

See here for supported languages.

Javascript must be enabled to submit anonymous comments - or you can login.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.