Peter Bridger Peter Bridger - 1 year ago 96
HTML Question

Autoscroll to bottom of DIV after updating, only if already at bottom of DIV before update

The code below adds content to a DIV and then scrolls it to show the new content:

<div id="Scrollable" style="height:400px; overflow:scroll;>
1<br />
2<br />
3<br />
4<br />

// Should DIV be auto scrolled?
var autoScroll = true;

// Add new content
$('#Scrollable').append('5<br />6<br />');

if ( autoScroll ){ // Scroll to bottom of DIV
$('#Scrollable').animate({ scrollTop: $('#Scrollable').prop('scrollHeight') });

What I need is a check at the
var autoScroll = true
stage to detect whether or not the DIV is currently scrolled to the bottom. So that after the new content is added, it will only autoscroll if the DIV was at the bottom before.

Answer Source

What problems did you encounter when trying to write this? Here's a jsFiddle example, based off the first result I found in Google for "jquery check if div is scrolled to bottom". It seems to work fine.

And here's a link to the article I found:

EDIT: Here's the actual code from the jsFiddle I posted, in case someone's searching and jsFiddle disappears. Have a scrollable div (give it a height and overflow-y: scroll) with an id of scrollable, and an inner div inside that with a class of inner. Then you can determine whether the div is scrolled to the bottom or not by using the following code:

var scrollable = $('#scrollable');
var inner = $('#scrollable > .inner');

// check if div is scrolled to bottom before addition of new content
var atBottom = Math.abs(inner.offset().top) + scrollable.height() + scrollable.offset().top >= inner.outerHeight();

// add additional content to .inner here

if ( atBottom ) {
  // do stuff like scroll to bottom etc
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download