How to get the real scroll height of div (say, inner text size)

kirly picture kirly · Nov 27, 2013 · Viewed 34.2k times · Source

I'm trying to make a auto-scrolling div that go to its top when it reaches the end. But it doesn't work...

function    scrollPannel()
{
    var pannel = document.getElementById('pannel');
    if (typeof scrollPannel.count == 'undefined')
    {
        scrollPannel.count = 0;
    }
    else
    {
        scrollPannel.count += 2;
    }
// trouble is here
    if ((scrollPannel.count - pannel.scrollHeight) > pannel.clientHeight)
    {
        scrollPannel.count = 0;
    }
    pannel.scrollTop = scrollPannel.count;
    setTimeout('scrollPannel()', 500);
}

HTML:

<div id='pannel'  style="height:200px;overflow:auto" onmouseover="sleepScroll()">
    <p>...</p><!-- long text -->
</div>

And after, I will need to find how to stop scrolling when "onmouseover" occures.

EDIT: I did not explained the problem clearly. In fact, I have tried something like:

if (scrollPannel.count > pannel.scrollHeight)
{
    scrollPannel.count = 0;
}

The problem is that scrollHeight seems greater than div inner text. So it makes a lot of time to return to the top.

So I need an element property of which I could use the value to compare with my count variable. However I don't know Javascript a lot and I could not find anything. I hope it is as well simple as I think of it.

Answer

kmcguire picture kmcguire · Sep 12, 2014

Try:

// calculate max scroll top position (go back to top once reached)
var maxScrollPosition = element.scrollHeight - element.clientHeight;
// example
element.scrollTop = maxScrollPosition;

That should do what you need.