Skip to content Skip to sidebar Skip to footer

Div Overflow Scroll-to-bottom: Is It Possible?

If I have a div with overflow:auto so that it is a scrollable div and I load it with information that makes a significant scroll area, is there a way that when I load the informati

Solution 1:

var myDiv = document.getElementById('myDiv');
myDiv.scrollTop = myDiv.scrollHeight;

Works in Firefox, Safari, Opera, Chrome and even Internet Explorer, which is more than I can say for the SSE test case I Set up... lol

I will spare you the rant about the obtuse solutions offered by others, and here is an example of code that could be used for an instant messaging type client.

document.body.onload = function()
{
    var myDiv = document.getElementById('myDiv');
    // Pick your poison below, server sent events, websockets, AJAX, etc.
    var messageSource = new EventSource('somepage');
    messageSource.onmessage = function(event)
    {
        // You must add border widths, padding and margins to the right.
        var isScrolled = myDiv.scrollTop == myDiv.scrollHeight - myDiv.offsetHeight;
        myDiv.innerHTML += event.data;
        if(isScrolled)
            myDiv.scrollTop = myDiv.scrollHeight;
    };
};

The part of that example that is relevant checks to see if the div is already scrolled to the bottom, and if it is, scrolls it to the bottom after adding data to it. If it is not already scrolled to the bottom, the div's scroll position will stay such that the visible content of the div is unaffected by adding the data.


Solution 2:

document.getElementById('mydiv').scrollTop = 9999999;

The scrollTop property specifies the scrolling offset in pixels from the top of the region. Setting it to a very large value will force it to the bottom.


Solution 3:

How about this?

function scroll_to_max(elm) { // {{{
    if(!scroll_to_max_el) {
        scroll_to_max_el = elm;
        setTimeout(scroll_to_max, 10); // Allow for the element to be updated
    } else {
        var el = scroll_to_max_el;
        var t = el.scrollTop;
        el.scrollTop = t+100;
        if(el.scrollTop != t) {
            setTimeout(scroll_to_max, 10); // Keep scrolling till we hit max value
        } else {
            scroll_to_max_el = null;
        }
    }
}
var scroll_to_max_el = null; // Global var!
// }}}

(NOTE: Only tested it in Chrome...)


Solution 4:

Late answer but this is much more helpful

$('#mydiv').scrollTop(($('#mydiv').height()*2));


Solution 5:

I think you need to set the scrollTop after the element is updated.

setTimeout(function (){ 
  el.scrollTop = 999999999
}, 10)

also, in chrome at least, 99999999999 will scroll to the bottom. but 999999999999 (an extra 9) will scroll to the top. it's probably converted to an int in the C side of webkit.


Post a Comment for "Div Overflow Scroll-to-bottom: Is It Possible?"