50

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.

7 Answers 7

71

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:

$(document).on('scroll', function() {
    var scroll = $(document).scrollTop();
    if (scroll < 1) {
        // Store eference to first message
        var firstMsg = $('.message:first');

        // Prepend new message here (I'm just cloning...)
        $('body').prepend(firstMsg.clone());

        // After adding new message(s), set scroll to position of
        // what was the first message
        $(document).scrollTop(firstMsg.offset().top);
    }
});

Demo: http://jsfiddle.net/GRnQY/

Edit: I noticed you wanted it with a button. You might have to do a little more math:

$(document).on('click', '#loadMore', function() {
    var firstMsg = $('.message:first');

    // Where the page is currently:
    var curOffset = firstMsg.offset().top - $(document).scrollTop();

    // Prepend
    firstMsg.before(firstMsg.clone());

    // Offset to previous first message minus original offset/scroll
    $(document).scrollTop(firstMsg.offset().top-curOffset);
});

Demo: http://jsfiddle.net/GRnQY/5/

7
  • 9
    The second solution is AWESOME - thank you very much, this was very helpful for implementing a "reverse infinite scroll" a la Facebook messages. Oct 22, 2012 at 19:48
  • If you are using ajax, add $(selector).scrollTop(firstMsg.offset().top-curOffset); on the ajax success attribute for the scroll to work properly
    – Ikhlak S.
    Nov 27, 2015 at 18:02
  • Awesome! Thank you Jeff!
    – Can Rau
    Jan 7, 2016 at 8:05
  • Some people coming here will probably just want to click a button without the button moving around. For this, calculations using firstMsg.offset() can insetad use the target element of the click event, making this snippet more portable: var curOffset = $(this).offset().top - $(document).scrollTop(); /* do stuff above the button */ $(document).scrollTop($(this).offset().top-curOffset); c.f. <jsfiddle.net/bwz8uLvt/1> (above demo but with button at arbitrary spot in the page)
    – ericP
    May 14, 2016 at 6:18
  • your 2nd solution really is great! thank you, I am still trying to understand why it works this way.
    – low_rents
    Jun 30, 2016 at 7:47
19

No need for jQuery here, just check for changes in the elements scrollHeight and adjust the scrollTop accordingly, ie:

var lastScrollHeight = el.scrollHeight;
for(var n=0; n<10; n++){
    // Prepend here...
}
var scrollDiff = el.scrollHeight - lastScrollHeight;
el.scrollTop += scrollDiff;

Demo

http://jsfiddle.net/fkqqv28e/

jQuery

To access the native DOM node from a jQuery collection, use array access; ie:

var lastScrollHeight = $('#myElement')[0].scrollHeight;
for(var n=0; n<10; n++){
    $('#myElement').prepend('<div>prepended '+Math.random()+'</div>');
}
var scrollDiff = $('#myElement')[0].scrollHeight - lastScrollHeight;
$('#myElement')[0].scrollTop += scrollDiff;
0
8

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:

someButton.on('click', function() {
    var curOffset = $(this).offset().top - $(document).scrollTop();
    // add content to your heart's content.
    $(document).scrollTop($(this).offset().top-curOffset);
});

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).

2

You could also keep the scroll position based on the offset to the bottom of the page/element.

var ScrollFromBottom = $(document).height() - $(window).scrollTop();

//ajax - add messages -- geenrate html code then add to dom

//set scroll position
$(window).scrollTop($(document).height() - ScrollFromBottom);
2

Here's a simple trick that worked for me:

// divWithTheScroll.prependElement...
divWithTheScroll.scrollTop += newlyPrependedElement.scrollHeight;
1

A little late. If you target modern browsers you should use Element.scrollIntoView()

The Element interface's scrollIntoView() method scrolls the element's parent container such that the element on which scrollIntoView() is called is visible to the user.

var element = document.getElementById("box");

element.scrollIntoView();
element.scrollIntoView(false);
element.scrollIntoView({block: "end"});
element.scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"});

1
  • Cool... I'll have to give it a try
    – Redtopia
    Jul 20, 2022 at 18:51
0

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.

// get old scroll top of '#sub_elem'
var oldScrollTop = $('#sub_elem').scrollTop();

// detach
var $els = $('#sub_elem').detach();

// complex processing on #sub_elem
// goes here

// attach
$('#main_el').attach($els);

// problem- always scrolls #sub_elem back to the top
// attempt #1: $('#sub_elem').scrollTop(oldScrollTop); // fails on mac Chrome
// attempt #2: use instant animation.  this works on mac Chrome
if (oldScrollTop) {
    $('#sub_elem').animate({
        scrollTop: oldScrollTop
    }, 0);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.