views:

881

answers:

1

Hi, I have two divs and two buttons:

<div id="container">
    <div id="items"></div>
</div>
<div id="up"></div>
<div id="down"></div>

How to continuously scroll '#items' until user releases the button? I tried using jquery mousedown event and animate function but couldn't make it to work.

$("#up").mousedown(function(){
$("#items").animate({"top": "+=10px"}, "fast");
})

The code above moves the div just once. I want to achieve continuous animation until the button is released. Thanks for your help!

+3  A: 

Please, try this:

var scrolling = false;

jQuery(function($){
    $("#up").mousedown(function(){
     scrolling = true;
     startScrolling($("#items"), "-=10px");
    }).mouseup(function(){
     scrolling = false;
    });
});

function startScrolling(obj, param)
{
    obj.animate({"top": param}, "fast", function(){
     if (scrolling)
     {
      startScrolling(obj, param);
     }
    });
}
micle
This works except you will get a js error that obj.animate is not a function on mouseup. A cleaner way to do this and avoid the js error is:if (!scrolling) { obj.stop();}else { obj.animate({"top": param}, "fast", function(){ if (scrolling) { startScrolling(obj, param); } });}
Mark