javascriptjquery-uijquery-pluginsjquery

How to prevent scrolling on prepend?


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?


Solution

  • 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.