jQuery prepend - prevent auto scroll

Prasanth picture Prasanth · Oct 17, 2012 · Viewed 8.9k times · Source

I was just working around with jQuery prepend and couldn't get it to work as expected.

What I am doing:

Prepending a .content div to #main div every one second

But, when I scroll down a bit [once the page is full of content], I keep getting scrolled back to #main's top or latest prepended .content

How do I:

Prevent the viewport from changing - like in case of append

Related fiddle

Answer

Brad Christie picture Brad Christie · Oct 17, 2012

As I explained in a comment, the scroll isn't actually changing. The window's scroll is based on "distance from top" (DfT). That is to say that if you have no scrollbar, you're DfT is 0. Once the scrollbars are introduced you now have a distance to work with.

Because the content is getting longer the viewport is only so many pixels high some content "falls off" the bottom of the page (prepend is making the DfT off by the height of your new element).

Best way I can think of is to counter it with the height of the new element. This allows you to scroll to a position then, as new elements are added, you modify the scroll position accordingly.

Here's an example of what I mean: http://jsfiddle.net/bradchristie/66RvC/1/

And the code (for reference):

var f = function(){
    var t = $(window).scrollTop(),      // Window's current scroll position
        $d = $(d()).prependTo('#main'), // store the new element
        h = $d.outerHeight();           // also get its height
    if (t){                             // Only adjust if they've scrolled
        $(window).scrollTop(t + h);     // add the delta to the scroll position
    }
    setTimeout( f, 1000 );
};