Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 755
fancy Avatar asked Apr 16 '11 17:04

fancy


People also ask

How do I stop my page from scrolling?

Disabling scroll with only CSS. There's another way to disable scrolling that is commonly used when opening modals or scrollable floating elements. And it is simply by adding the CSS property overflow: hidden; on the element you want to prevent the scroll.

How do you stop background scrolling in CSS?

To hide the scrollbar and disable scrolling, we can use the CSS overflow property. This property determines what to do with content that extends beyond the boundaries of its container. To prevent scrolling with this property, just apply the rule overflow: hidden to the body (for the entire page) or a container element.

How do I restrict scrolling in HTML?

Set overflow-x to hidden to Disable Horizontal Scroll Bar in CSS. We can use the overflow-x property and set it to hidden to disable the horizontal scroll bar in CSS. We can test the disabling of the scroll bar horizontally by limiting a text to only one line.


2 Answers

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 :)

like image 90
Sheraff Avatar answered Oct 06 '22 03:10

Sheraff


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.

like image 31
Groovetrain Avatar answered Oct 06 '22 03:10

Groovetrain