Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 information, the div shows the bottom results? Or essentially scrolls to the bottom?

I've seen jQuery solutions but this is for use in an HTA so I cannot use jQuery. Is there a purely javascript way to accomplish this?

like image 460
thepip3r Avatar asked Jan 05 '11 16:01

thepip3r


2 Answers

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.

like image 98
Joshua W Avatar answered Oct 19 '22 17:10

Joshua W


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.

like image 33
Phrogz Avatar answered Oct 19 '22 18:10

Phrogz