Poor man's dynamic scroll to bottom

July 2016 ยท 2 minute read

I feel obliged to explain what I mean by “dynamic scroll to bottom”. I will do so with an example; When you have a div with the ability to overflow vertically: when scrolled to top, it will not go down when content is appended within it - it will stay scrolled to top. If data is prepended, then it will stick to the top and expose the new content. Conversly, when scolled to bottom, appended content will not be shown unless if you manually scroll down. This is terrible for chat UIs and something which I have dealt with in the past which I can best refer to as “Scrolled to top by default”. But say you wanted to have an element “scrolled to bottom by default”?

No simple plugin or HTML quirks support this natively which is why we are forced to use some sort of javascript hack.

The heart of this hack is simple: Every few milliseconds (100 is a good number), the element will scroll to bottom with the exception if it has been manually scrolled up.

//Has the user scrolled? switch
var scrolled = false;

function updateScroll(){
    if(!scrolled){
        //Scroll to bottom is user has scrolled
        var objDiv = $("#elementid")[0];
        objDiv.scrollTop = objDiv.scrollHeight;
    }
}

//Detect if scrolled to bottom
function isScrolled() {
    var node = $("#elementid")[0];
    return (node.scrollTop + node.offsetHeight === node.scrollHeight);
}

//Control switch
$("#elementid").scroll(function() {
   if(isScrolled()) {
      //User scrolled to bottom, get sticking it there
      scrolled = false;
   } else {
      //User scrolled away from bottom, unlock
      scrolled = true;
   }
});


//Final piece
setInterval(updateScroll,100);

Obviously, this will require JQuery but it can be rewritten to use VanillaJS - I just have no stake to do so. I might however write this into a jquery plugin some time.