[ACCEPTED]-How to prevent scrolling on prepend?-jquery

Accepted answer
Score: 43

I believe the most universal way to do this 5 would be to simply measure the document 4 height before and after you've modified 3 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 2 the window moving away from the content 1 you're reading :)

Score: 20

I've done it in the past by prepending the 4 elements, then calculating their total outerheight, and 3 setting the scrolltop to that value. Something 2 like this:

var $current_top_element = $('body').children().first();

var previous_height = 0;
$current_top_element.prevAll().each(function() {
  previous_height += $(this).outerHeight();


Hope this points you in the right 1 direction.

Score: 9

I took a slightly different approach:

Start 14 by getting the first element of the body 13 (or of another element if you're pretending 12 to an element other than the body which 11 is what I needed), then after prepending 10 the new set of elements, use the offset (if need 9 to scroll relative to body) or the position (if 8 need to scroll relative to an ancestor element) function 7 on the original first element to get its 6 updated coordinates and scroll to that point.

Something 5 like:

var current_top_element = $('body').children().first();


Or for something other than body scroll:

var current_top_element = $('#ul-element-id li:first'); //example with a list


Be 4 aware that position() returns the element's position 3 relative to its offset parent , so make sure to set the 2 css position attribute of your parent element 1 as needed ( http://api.jquery.com/offsetParent/ )

For more details refer to: http://api.jquery.com/category/offset/

Score: 6

I know, I'm very late to that topic. Sorry 7 for undigging it, but I discovered a very 6 simple way for preventing scrolling to top 5 when you prepend elements to the body.

The 4 auto-scrolling appends when the scroll Y-position 3 is at zero. Simply do this :

element.scrollTo(0, 1);

And your element 2 won't automatically go to the top after 1 the prepend.

Score: 0

For worked this vanilla JS solution:

const currentFirstElement = parentElement.firstChild
      elementsToPrepend.forEach((element) => {

         // keep the current first element in the view port
             block: 'start',
             behavior: 'auto',


More Related questions