Chris Roberts
Chris Roberts

Reputation: 18802

How do I get the height of a <DIV> not including the horizontal scrollbar using JQuery?

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!

Upvotes: 4

Views: 2021

Answers (2)

BalusC
BalusC

Reputation: 1108672

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

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

Upvotes: 8

Dan Herbert
Dan Herbert

Reputation: 103397

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.

Upvotes: 1

Related Questions