views:

93

answers:

2

Hi,

I am writing a jQuery plugin which makes use of two nested <DIV> elements.

The outer div has a fixed width with overflow:scroll and the inner div (which is much wider) contains the content which I want to scroll around.

This all works fine apart from the fact that I want to use some JavaScript (with jQuery) to set the height of the inner div to exactly match the height of the outer div, less the height of the horizontal scroll bar.

At the moment I'm setting it to the height of the outer div, less about 20 pixels. This sort of works, but it's not going to be browser independent and is definately a hack!

Any help would be very much appreciated!

+1  A: 

I found a function which can get the width of a scrollbar

function getScrollBarWidth () {  
    var inner = document.createElement('p');  
    inner.style.width = "100%";  
    inner.style.height = "200px";  

    var outer = document.createElement('div');  
    outer.style.position = "absolute";  
    outer.style.top = "0px";  
    outer.style.left = "0px";  
    outer.style.visibility = "hidden";  
    outer.style.width = "200px";  
    outer.style.height = "150px";  
    outer.style.overflow = "hidden";  
    outer.appendChild (inner);  

    document.body.appendChild (outer);  
    var w1 = inner.offsetWidth;  
    outer.style.overflow = 'scroll';  
    var w2 = inner.offsetWidth;  
    if (w1 == w2) w2 = outer.clientWidth;  

    document.body.removeChild (outer);  

    return (w1 - w2);  
};  

OS Scrollbars are uniform in width, whether displayed vertically or horizontally, so you can use the width returned as the height of a horizontal scrollbar.

Edit: My original code same didn't work, however I've updated my code to a working function. You can see it in action here: http://jsbin.com/ejile3

The page will alert the width of the scrollbar.

Dan Herbert
Thanks for your answer, but the clientHeight suggested by BalusC did the job for me in this instance.
Chris Roberts
+6  A: 

You need to use element.clientHeight. In jQuery that would be something like:

var heightWithoutScrollbar = $('#outer')[0].clientHeight;
BalusC