detect if scrollbars are visible inside a div

A

andrew.neale

Hello,

I have a div that has an overflow set to auto. I would like to know if
the scrollbars are visible in javascript.

Any help is appreciated.

Thanks
 
A

andrew.neale

I think I have sorted the problem

if (document.getElementById('divID').scrollHeight >
document.getElementById('divID').clientHeight)
{
//a scroll bar is present
}
else
{
//a scroll bar is NOT present
}

can anyone see any problems with this?
 
C

Csaba Gabor

I think I have sorted the problem

if (document.getElementById('divID').scrollHeight >
document.getElementById('divID').clientHeight) ....
can anyone see any problems with this?

The below code fails to detect a horizontal scroll bar on Firefox

<div id=div1 style="border:1px solid
red;width:120px;height:50px;overflow:auto">
There_once_was_a_boy_from_nod_Who_carried_a_lot_of_sod</div><br>

<div id=div2 style="border:1px solid
red;width:120px;height:50px;overflow:auto">
There once was a boy from nod Who carried a lot of sod</div>

<script type='text/javascript'>
function scrollDetect(elemId) {
var elem = document.getElementById(elemId);
if (elem.scrollHeight > elem.clientHeight) {
alert("code says scroll bar is present on '" +
elemId + "'\n" + elem.scrollHeight +
", " + elem.clientHeight);
} else {
alert("No scroll bar detected for '" +
elemId + "'\n" + elem.scrollHeight +
", " + elem.clientHeight);
}
}
scrollDetect('div1');
scrollDetect('div2');
</script>

Csaba Gabor from Vienna
 
G

Gérard Talbot

I think I have sorted the problem

if (document.getElementById('divID').scrollHeight >
document.getElementById('divID').clientHeight)
{
//a scroll bar is present

Correction: a vertical scrollbar is rendered.
}
else
{
//a scroll bar is NOT present

Correction: a vertical scrollbar is not rendered.
}

can anyone see any problems with this?

You need to do the same for clientWidth and scrollWidth to detect the
presence of an horizontal scrollbar.
Finally, your code should get to know what is the current/computed css
overflow value because the client vs scroll comparison is equal for
overflow: scroll when there is nothing to scroll actually. So, the
scrollbar is present and rendered but your code fails to detect this for
both scrollbars.

Gérard
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top