Search code examples
jqueryhtmlscrollbindsmoothing

jQuery- vertical div scroll with buttons won't scroll continuously


so I have a div that looks like <div id="scroller">...</div> and inside this div is a bunch of content and the overflow is set to hidden.

I am attempt to make a smooth scrolling vertical div. I have a button on top of the div id='up' and a button on the bottom id='down'.

Right now when I click the up or down buttons the div will scroll, but only about 1 or 2 lines (each click).

Can someone please explain to me how I would bind this function so it continuously scrolls while the mouse is pressed down? Also, it feels more like a click up/down rather than a smooth scroll.

Is there a different function I should use rather than scrollTop()?

Heres a FIDDLE

Any help with this would be great! Thanks in advance.

$(document).ready(function() {
    var timeoutId = 0;

function scrollIt(amount){
    $('#scroller').scrollTop($('#scroller').scrollTop()+amount);
}

$('#down').mousedown(function() {
    timeoutId = setTimeout(scrollIt(5), 1000);
}).bind('mouseleave', function() {
    clearTimeout(timeoutId);
});

$('#up').mousedown(function() {
    timeoutId = setTimeout(scrollIt(-5), 1000);
}).bind('mouseleave', function() {
    clearTimeout(timeoutId);
});
});

WORKING SOLUTION

$(document).ready(function() {
    var timeoutId = 0;

    function scrollIt(amount){
$('#scroller').scrollTop($('#scroller').scrollTop()+amount);
}

$('#down').mousedown(function() {
    timeoutId = setInterval(function(){scrollIt(5)}, 20);
}).bind('mouseup mouseleave', function() {
    clearInterval(timeoutId);
});

$('#up').mousedown(function() {
    timeoutId = setInterval(function(){scrollIt(-5)}, 20);
}).bind('mouseup mouseleave', function() {
    clearInterval(timeoutId);
});
});

HTML

<div class="scrollup" id="up">&nbsp;</div> 

 <div id="scroller" class="scroller buttongroup">  
    blah blah
    content blah
    blah blah
    content blah
</div>

<div class="scrolldown" id="down">&nbsp;</div> 

Solution

  • You have two problems:

    1. the onmousedown event is only fired once, not repeatedly, so a single call to setTimeout will only happen once. The solution is to use setInterval (and clearInterval respectively) to have the method be repeatedly called until the interval is cleared

    2. The first parameter to setTimeout/setInterval must be a function. You're actually passing the return value of scrollIt(5) which is undefined. You have to pass the actual function itself, i.e. just scrollIt. That of course leaves you with the problem of not being able to tell it whether to add 5 or subtract 5. You can solve that by simply wrapping the call in anonymous function and passing that:

      setInterval(function(){ scrollIt(5) }, 1000)
      

    Also, 1000 milliseconds is a very slow interval for something like scrolling. You need to knock that down to about 250. Here's an updated fiddle with all these changes in effect.