jQuery prepend - prevent auto scroll
Asked Answered
R

1

5

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

Riggins answered 17/10, 2012 at 18:12 Comment(2)
The view isn't changing; the page becomes longer so scroll distance from top is static while the full page length becomes dynamically larger (thus bottom elements go beyond viewport). Are trying to make it so if you scroll all the way to the bottom of the page the last element stays in view instead of "falling off"?Pentomic
@BradChristie I basically want 'what is visibile' [except the scroll bar, which obviously should change] to not change at all irrespective of prepends.Riggins
P
13

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 );
};
Pentomic answered 17/10, 2012 at 18:24 Comment(5)
And, append has nothing to do with DfT and I didn't have any problem. Right?Riggins
@goldenparrot: Not that it has no relevance, it's just that append doesn't shift a lot of elements down. However, if you had two lists on a page and you keep appending elements to the list on top, the second lists' elements would shift and you'd have the same problem.Pentomic
@goldenparrot: An example of what I mean here (using append instead of prepend). Notice it matters now with content after it.Pentomic
Thank you. I think I got the gist of it now.Riggins
This is exactly what I was looking for. Thanks for the solution and the explanation about the "DfT". :DBibliotherapy

© 2022 - 2024 — McMap. All rights reserved.