This Question have 3 answers right now.

Scrolling Overflowed DIVs with JavaScript

Question!

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!



Answers

Try using:

$("#thediv").css("overflow", "scroll")
By : Sumeet


I had a div wrapping 3 divs that were floating left, and whose contents were being resized. It helps to turn funky-colored borders/background on for the div-wrapper when you try to resolve this. The problem was that the resized div-content was overflowing outside the div-wrapper (and bled to underneath the area of content below the wrapper).

Resolved by using @Shog9's answer above. As applied to my situation, this was the HTML layout:

<div id="div-wrapper">
  <div class="left-div"></div>
  <div id="div-content" class="middle-div">
  Some short/sweet content that will be elongated by Jquery.
  </div>
  <div class="right-div"></div>
</div>

This was the my jQuery to resize the div-wrapper:

<script>
$("#div-content").text("a very long string of text that will overflow beyond the width/height of the div-content");
//now I need to resize the div...
var contentHeight = $('#div-content').prop('scrollHeight')
$("#div-wrapper").height(contentHeight);
</script>

To note, $('#div-content').prop('scrollHeight') produces the height that the wrapper needs to resize to. Also I am unaware of any other way to obtain the scrollHeight an actual jQuery function; Neither of $('#div-content').scrollTop() and $('#div-content').height would produce the real content-height values. Hope this helps someone out there!



$("#thediv").scrollTop($("#thediv")[0].scrollHeight);


Video about Scrolling Overflowed DIVs with JavaScript