Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scrolling Overflowed DIVs with JavaScript

I've got a div that uses overflow:auto to keep the contents inside the div as it is resized and dragged around the page. I'm using some ajax to retrieve lines of text from the server, then append them to the end of the div, so the content is growing downwards. Every time this happens, I'd like to use JS to scroll the div to the bottom so the most recently added content is visible, similar to the way a chat room or command line console would work.

So far I've been using this snippet to do it (I'm also using jQuery, hence the $() function):

$("#thediv").scrollTop = $("#thediv").scrollHeight; 

However it's been giving me inconsistent results. Sometimes it works, sometimes not, and it completely ceases to work if the user ever resizes the div or moves the scroll bar manually.

The target browser is Firefox 3, and it's being deployed in a controlled environment so it doesn't need to work in IE at all.

Any ideas guys? This one's got me stumped. Thanks!

like image 619
Bob Somers Avatar asked Aug 16 '08 21:08

Bob Somers


People also ask

How to create scrollable Div in JavaScript?

Use the overflow Property to Scroll a div Element in JavaScript. The overflow property for the value auto will automatically create a vertical scrollbar if the content is larger than the div size. This one property will solve the case of making a scrollable div element.

How to fix overflowing Div?

Add a padding top on the #scrollable div and make the #menu div absolute. Add a z-index to the #menu div so it stays on top. Also, make sure to add box-sizing: border-box on all elements to prevent exceeding the assigned sizes.

Why content overflowing out of Div?

The overflow property controls what happens to content that breaks outside of its bounds: imagine a div in which you've explicitly set to be 200px wide, but contains an image that is 300px wide. That image will stick out of the div and be visible by default.


1 Answers

scrollHeight should be the total height of content. scrollTop specifies the pixel offset into that content to be displayed at the top of the element's client area.

So you really want (still using jQuery):

$("#thediv").each( function()  {    // certain browsers have a bug such that scrollHeight is too small    // when content does not fill the client area of the element    var scrollHeight = Math.max(this.scrollHeight, this.clientHeight);    this.scrollTop = scrollHeight - this.clientHeight; }); 

...which will set the scroll offset to the last clientHeight worth of content.

like image 152
Shog9 Avatar answered Sep 21 '22 13:09

Shog9