How to get the height of a <DIV> without including a horizontal scrollbar using jQuery?

I am writing a jQuery plugin that uses two nested <DIV> elements.

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

All this works great, except that I want to use some JavaScript (with jQuery) to set the height of the inner div exactly to the height of the outer div, minus the height of the horizontal scrollbar.

I am currently setting it to the height of the outer div, less than 20 pixels. Such works, but it will not be browser independent and certainly a hack!

Any help would be greatly appreciated!

+4
source share
2 answers

You need to use element.clientHeight . In jQuery, it will be something like:

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

I found a function that can get the scrollbar width

 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 have the same width, regardless of whether they are displayed vertically or horizontally, so you can use the width returned as the height of the horizontal scrollbar.

Edit: My source code did not work, however I updated my code to a working function. You can see it in action here: http://jsbin.com/ejile3

The page will warn the scrollbar width.

+1
source

All Articles