I have a page that displays messages and I want it to work just like Facebook, but without the lazy loader. Messages are displayed in chronological order, most recent last.
My message list is initially populated x number of most recent messages, and the window is scrolled to the bottom. When the user starts to read the thread, they read from bottom to top. If they get to the top, they can load more messages... I make them click a button... facebook has a lazy loader. New messages are prepended to the list.
Problem: As the new messages are prepended, the existing messages are pushed down, causing the user to lose their "viewing" place. How can I keep the user's current view position as I add the new messages? For an example, open a long message thread in facebook, scroll to the top causing new messages to be added... your view location doesn't change even though the scroll position does.
Store a reference to the first message before you prepend new messages, and after you prepend, set the scroll to the offset of that message:
Demo: http://jsfiddle.net/GRnQY/
Edit: I noticed you wanted it with a button. You might have to do a little more math:
Demo: http://jsfiddle.net/GRnQY/5/
Some folks coming here may just want to add content without the current focus jumping around. Modifying Jeff B's demo above to use the click event target makes this idiom more portable:
c.f. http://jsfiddle.net/bwz8uLvt/1/ (variant of Jeff B's demo above but with the [add more] button at an arbitrary point in the page).
I just ran across a variation of this. i detached a large number of elements, processed them and then attached them again. this doesn't complete synchronously in Chrome so i could not set $el.scrollTop(oldval) reliably. I found this solution worked for me.
You could also keep the scroll position based on the offset to the bottom of the page/element.
Here's a simple trick that worked for me:
No need for jQuery here, just check for changes in the elements scrollHeight and adjust the scrollTop accordingly, ie:
Demo
http://jsfiddle.net/fkqqv28e/
jQuery
To access the native DOM node from a jQuery collection, use array access; ie: