views:

265

answers:

2

I want to detect the presence of a scroll bar in a DIV using jQuery. I was thinking to use $('div').scrollTop() but that returns 0 in both cases when the scroll bar is at the top and when there is no scroll bar at all.

Any ideas guys?

+4  A: 

Assuming overflow on the div is auto:

var div= document.getElementById('something'); // need real DOM Node, not jQuery wrapper
var hasVerticalScrollbar= div.scrollHeight>div.clientHeight;
var hasHorizontalScrollbar= div.scrollWidth>div.clientWidth;
bobince
This works too. Thanks. But unlike in my solution example I posted, In the real world I don't have "IDs" to work with, i am selecting the DIV using jQuery CSS selectors...
Roberto Sebestyen
Then use `jQueryElement.get(0)` to get the real DOM node from it http://api.jquery.com/get.
BalusC
Whilst this is really useful, is it really the correct answer since it doesn't use any jQuery at all?
Dan Diplo
A: 

Well I ended up finding a solution by doing the following:

Wrap the content that grows with a DIV, then I detect if a (vertical) scroll bar is present by comparing the height of wrapperDiv with the height of containerDiv (which normally has the scroll bar if the content is too large).

If the height of wrapperDiv is bigger than the height of containerDiv then there is a scroll bar, if it is smaller, then there is no scroll bar.

<DIV id="containerDiv" style="width:100px;height:100px;overflow:auto;">
    <DIV id="wrapperDiv">
        .... content here...
    </DIV>
</DIV>
Roberto Sebestyen
Did you try bobince's solution? His seems like it would work without the extra wrapper div.
Justin Johnson
wasn't that the answer from the second link i posted? http://stackoverflow.com/questions/2059743/detect-elements-overflow-using-jquery
moi_meme
Yes bobince's solution would work, but unlike in the example i gave above I don't actually have "IDs" to work with. I'm selecting using jQuery CSS selectors, so I can't use getElementById in order to access clientHeight(). plus I dont trust the raw .clientHeight value as I think it returns slightly different numbers in different browsers, doesen't it?
Roberto Sebestyen