views:

223

answers:

3

I get the width of the browser using the following line:

$(document).width()

and then I set the element to this width.

But in IE, the horizontal scrollbar appears (width is larger than the browser size - I think this is because it counts the width of vertical scrollbar). I use the html 4.0 transition doctype. What should I do?

+1  A: 

It shouldn't count the scollbar. Does your element have margin or border? That would be added to the width of the element and affect the horizontal scrolling. Just try subtracting from the $(document).width() value.

gWiz
The difference is due to the doctype. It works fine in XHTML 1.0 doctype.
Billy
+4  A: 

Try the clientWidth property, like so:

$('body').attr('clientWidth')

From the Mozilla Developer Center:

clientWidth is the inner width of an element in pixels. It includes padding but not the vertical scrollbar (if present, if rendered), border or margin.

From MSDN:

Retrieves the width of the object including padding, but not including margin, border, or scroll bar.

No Surprises
A: 

You can use $(window).width(), which doesn't include the scrollbar. However, that's the window width not the document width. The document can be a lot wider than the window in horizontal scrollbar situations. If your page will never get wide enough for a horizontal scrollbar, this may be fine for you.

Getting the scrollbar-less document width in IE (Quirksmode), regardless of the existence of a horizontal scrollbar, I know of no perfect solution. This is what I'm currently using:

var maxLikelyScrollbarWidth = 25; // It's 20px on my IE
var hscroll = $(document).width() > $(window).width() + maxLikelyScrollbarWidth;
var widthNoScrollbar = hscroll ? $(document).width() : $(window).width();

It's not perfect but does the job. There are edge cases though.

darkporter