Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 884
kirly Avatar asked Nov 27 '13 15:11

kirly


2 Answers

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.

like image 159
kmcguire Avatar answered Sep 28 '22 06:09

kmcguire


You could try using the scrollHeight property.

https://developer.mozilla.org/en-US/docs/Web/API/element.scrollHeight

like image 41
kkaosninja Avatar answered Sep 28 '22 06:09

kkaosninja