John
John

Reputation: 3115

Autoscrolling after timeout

I have an element, of id list that I want to auto scroll to the bottom and then back to the top continuously, but should stop scrolling to allow the user to control scroll. After a certain amount of time that the user has not "mousemove mousedown" on the element, the element should begin to auto scroll again.

I'm having difficulty managing the timeouts(for auto scroll up after auto scroll down) and interval(for continues autoscrolling up and down) and "mousemove mousedown" events and stopping the animation once those events occur. My code was a jumbled mess.

My scroll down:

$("#list").animate({
scrollTop : $("#list")[0].scrollHeight
}, timeDown);

Scroll up:

$("#list").animate({
    scrollTop : 0
}, timeUp);

Upvotes: 2

Views: 706

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206101

http://jsbin.com/oqadud/3/edit

$list   = $('#list');
$listSH = $list[0].scrollHeight - $list.outerHeight();

function loop(){ 
  var t = $list.scrollTop();
  $list.stop().animate({scrollTop : !t ? $listSH : 0 }, 2000, loop);
}
loop();

$list.on('mouseenter mouseleave', function( e ){
  return e.type=="mouseenter"? $list.stop() : loop();
});

$listSH will return actually the Available scrollHeight, than you can use the animate callback to recall the function loop() that will loop our animation.

inside the loop we just need to get the current $list.scrollTop(); position - in case of mouseleave or any other circumstance so we can ask a ternary operator ( ? : ) what to do in case the boolean !t (is0==false) animate to $listSH else animate to 0.

on DOM ready you call/start your loop()

and on 'mouseenter mouseleave' grab the event and again inside a ternary operator do:
IF event == mouseenter : .stop() any animation
ELSE : restart our loop() function (as I said, from the current scrollTop()).

Upvotes: 2

Related Questions