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 read
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 :)
I know, I'm very late to that topic. Sorry for undigging it, but I discovered a very simple way for preventing scrolling to top when you prepend elements to the body.
The auto-scrolling appends when the scroll Y-position is at zero. Simply do this :
element.scrollTo(0, 1);
And your element won't automatically go to the top after the prepend.
I've done it in the past by prepending the elements, then calculating their total outerheight, and setting the scrolltop to that value. Something like this:
var $current_top_element = $('body').children().first();
$('body').prepend(other_elements);
var previous_height = 0;
$current_top_element.prevAll().each(function() {
previous_height += $(this).outerHeight();
});
$('body').scrollTop(previous_height);
Hope this points you in the right direction.
I took a slightly different approach:
Start by getting the first element of the body (or of another element if you're pretending to an element other than the body which is what I needed), then after prepending the new set of elements, use the offset (if need to scroll relative to body) or the position (if need to scroll relative to an ancestor element) function on the original first element to get its updated coordinates and scroll to that point.
Something like:
var current_top_element = $('body').children().first();
$('body').prepend(other_elements);
$('body').scrollTop(current_top_element.offset().top);
Or for something other than body scroll:
var current_top_element = $('#ul-element-id li:first'); //example with a list
$('#ul-element-id').prepend(other_elements);
$('#ul-element-id').scrollTop(current_top_element.position().top);
Be aware that position() returns the element's position relative to its offset parent , so make sure to set the css position attribute of your parent element as needed ( http://api.jquery.com/offsetParent/ )
For more details refer to: http://api.jquery.com/category/offset/