Alan C
Alan C

Reputation: 1

scrollTop not working correctly with .animate

I have a Div containing overflow text that I would like to scroll through with the click of a corresponding button. It's set to scroll 100 pixels in either direction. The function works fine when I use it don't use jQuery .animate.

$(function() {
   $( "#upBtn" ).click(function(){
    $('#scroll').scrollTop($('#scroll').scrollTop()-100);
}); 

 $( "#downBtn" ).click(function(){
    $('#scroll').scrollTop($('#scroll').scrollTop()+100);
});

But once I add .animate, I can only click the button once in either direction. It won't let me scroll down past the first 100 pixels.

 $("#scroll").animate({ scrollTop: "100px" });

Any suggestions? I put together a codepen.

Upvotes: 0

Views: 268

Answers (1)

Jai
Jai

Reputation: 74738

Yes that is correct behavior!

Why?

Because that is already at 100px so it doesn't scroll further than that.

What should be done:

You can get the current scroll top position and add 100px to it. Like below:

 $("#scroll").animate({ scrollTop:  $("#scroll").scrollTop() + 100 });

And same goes for other way up.

Upvotes: 1

Related Questions