Scroll to bottom of a div

Allow user to scroll and maintain position with “Scroll To Bottom of the  Div” example

Well I am getting tired of being emailed the same question about my entry Scroll To Bottom of a Div. So I sat down in a few minutes I  came up with this. My first attempt used onscroll, but it Opera appears to not  supporet onscroll on a div. So I had to twidle my thumbs and realized I just had  to use the last know position as a reference. Duh…

So how do I keep the scroll position of a div if the user scrolls it and also  allow for it to stick to the bottom?

Put this code in your head:

  var chatscroll = new Object();

  chatscroll.Pane = function(scrollContainerId){
    this.bottomThreshold = 20;
    this.scrollContainerId = scrollContainerId;
    this._lastScrollPosition = 100000000;

  chatscroll.Pane.prototype.activeScroll = function(){

    var _ref = this;
    var scrollDiv = document.getElementById(this.scrollContainerId);
    var currentHeight = 0;

    var _getElementHeight = function(){
      var intHt = 0;
      if( =;
      else intHt = scrollDiv.offsetHeight;
      return parseInt(intHt);

    var _hasUserScrolled = function(){
      if(_ref._lastScrollPosition == scrollDiv.scrollTop || _ref._lastScrollPosition == null){
        return false;
      return true;

    var _scrollIfInZone = function(){
      if( !_hasUserScrolled ||
          (currentHeight - scrollDiv.scrollTop - _getElementHeight() <= _ref.bottomThreshold)){
          scrollDiv.scrollTop = currentHeight;
          _ref._isUserActive = false;

    if (scrollDiv.scrollHeight > 0)currentHeight = scrollDiv.scrollHeight;
    else if(scrollDiv.offsetHeight > 0)currentHeight = scrollDiv.offsetHeight;


    _ref = null;
    scrollDiv = null;


Create a new instance with the name of the div;

var divScroll = new chatscroll.Pane('divExample');

When ever you add something to the div call the method activeScroll


And the magic will occur.

I tested this on Win XP with IE6, Firefox 1.5, Netscape 8.04, Mozilla 1.7.12,  and Opera 8.5.1 with no issues. My MAC testers came through: Safari 2.0.4,  Camino 1.0.2int, Firefox, and Opera 9.0.1 are good. Minor issue with  Opera 8.52 and touchpad. I don’t think that is a show stopper.

Eric Pascarello Coauthor of Ajax In Action Moderator of HTML/JavaScript at Author of: JavaScript: Your Visual Blueprint for building Dynamic  Web Pages


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s