How to prevent scrolling on prepend?

fancy picture fancy · Apr 16, 2011 · Viewed 16.8k times · Source

I'm prepending content to the top of the body. Sometimes this content can be 400-500px tall, and when something like this gets added, pushing the content down when you are reading the page it can be really annoying.

I want the items to be automatically prepended, not something like click here to see new items.

Is there any way to prepend this content to the top of the body without moving the page? Then when a user scrolls to the top it is just there already?

Answer

Sheraff picture Sheraff · Feb 1, 2014

I believe the most universal way to do this would be to simply measure the document height before and after you've modified it:

var old_height = $(document).height();  //store document height before modifications
var old_scroll = $(window).scrollTop(); //remember the scroll position

//do anything
$("p:first").prepend( "<p>I just became first</p>" );

$(document).scrollTop(old_scroll + $(document).height() - old_height); //restore "scroll position"

That way you can really do anything without the window moving away from the content you're reading :)