When adding data to a document with a vertical slope, how can I keep the previous part visible?

This is part of an infinite scroll that also works when we scroll up:

<div id="sContainer"> <div class="message0">Initial Content 111</div> <div class="message1">Initial Content 222</div> <div class="message2">Initial Content 333</div> <div class="message3">Initial Content 444</div> <div class="message4">Initial Content 555</div> <div class="message5">Initial Content 666</div> <div class="message6">Initial Content 777</div> </div> 

JS Code:

 var dataAbc = '<div class="message7">Focus Shifted Here</div>'; setTimeout(function(){ $(dataAbc).prependTo("#sContainer");},3000); setTimeout(function(){ $(dataAbc).prependTo("#sContainer");},3000); setTimeout(function(){ $(dataAbc).prependTo("#sContainer");},3000); setTimeout(function(){ $(dataAbc).prependTo("#sContainer");},3000); 

Js Fiddle: http://jsfiddle.net/LRLR/ocfLkxex/

Question:

When prependTo is called, the data is pushed down, and new data is added at the top. The scrollbar seems to ignore this, and, from the point of view of users, everything he read is reset. After several times that the user is reading, it is pushed out of the visible area, and the user must scroll down to continue reading.

Desired:

I want the user to be able to read long content without having to (re) scroll when new items are added at the top of the list. Ideally, if the user scrolls so that the β€œInitial Content 444” is at the top of the view when new items are added, he should maintain his visual position. New items should be added β€œabove” without visually moving the current content.

Why doesn't the scrollbar keep these elements already visible?
How do I customize the scroll bar to behave the way I want?

+5
source share
1 answer

This is an obvious behavior. You add new elements that change the height if the content. This changes the value of body scrollTop .

What you can do is calculate the total height of the added content (plus the fields), and after adding the new content you should reset body / html scrollTop with the old content height with scroll up / down.

Then your meta example would be something like this:

 setTimeout(function () { var top = $('body').scrollTop(); top += $(dataAbc).prependTo("#sContainer").outerHeight() + 10; top += $(dataAbc).prependTo("#sContainer").outerHeight() + 10; top += $(dataAbc).prependTo("#sContainer").outerHeight() + 10; $('body, html').scrollTop(top); }, 3000); 

Demo: http://jsfiddle.net/ocfLkxex/1/

Note I programmed a magic number 10 for the field value, in your case you can use a constant or calculate it dynamically, of course (preferably, for example, .css('marginTop') ).

+7
source

Source: https://habr.com/ru/post/1207967/


All Articles