Alex Rivera | Logout

How to prevent scrolling on prepend?

Asked 2011-04-16T17:43:29.967
44

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?

Edit
Report

1 Answer

10

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/

answered 2012-10-05T05:22:29.503

Your Answer