Tuesday, 21 December 2010

JQuery Vertical Scroller

useful chunk of code for scrolling a list of something, vertically using JQuery

an example of the list html

<ul id="list">
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
</ul>

this is the jquery

<script type="text/ecmascript">
var list = $("#list");
list.addClass("scrolllist");
list.wrap("<div class=\"clipper_container vert\"></div>").wrap("<div class=\"clipper\"></div>");
var clip = list.parent();
var container = clip.parent();
var items = list.children();
var targetHeight = 0;
items.each(function () { targetHeight += $(this).height() });
var cumulativeHeight = 0;
items.each(function () { cumulativeHeight += $(this).height() });
while (cumulativeHeight < targetHeight * 3) {
items.clone().appendTo(list);
items = list.children();
cumulativeHeight = 0;
items.each(function () { cumulativeHeight += $(this).height() });
}
list.css({ "height": cumulativeHeight + "px" });
var interval = setInterval(function () {
if (clip[0].scrollTop == targetHeight) {
clip[0].scrollTop = 1;
}
else {
clip[0].scrollTop += 1;
}
}, 10);
</script>

and the css

/* css for Scrolling element */

.clipper_container
{
position: relative;
}
.clipper
{
position: relative;
overflow: hidden;
z-index: 2;
height: 493px;
width:144px;
}


.scrolllist
{
position: absolute;
top: 0;
left: 0;
z-index: 1;
overflow: hidden;
margin: 0;
padding: 0;
list-style: none;
height: 493px;
width: 150px;
margin: 0px;
padding: 0px;
}


.scrolllist li
{
list-style-type: none;
padding: 0px;
margin: 0px;
text-align:center;
}

.vert
{
/* wider than clip to position buttons to side */
width: 150px;
height: 493px;
margin-bottom: 1.5em;
}

.clipmain, .scolllistmain, .vertmain
{
height:600px;
}


An additional Development I have made for the scroller is to have a stepped scroll using animate.

To do this simply replace the interval variable stated above with the following
var interval = setInterval(
function () {
var target = targetHeight + list.position().top;
if(target == -50)
{
list.css({top:-50});
}
list.animate({ top: '-=50' }, "fast");
}, 1000);

No comments:

Post a Comment