Get the scrollbar width

Dynamic Javascript

Although the DOM provides access to several aspects of the window host object,A scrollbar some important information can only be estimated or indirectly calculated. The width of the scrollbar is one of those crucial details that may break or indeed make a pixel perfect layout. On Windows systems, this is a preference that can be set by right-clicking on the desktop, choosing the Properties option from the contextmenu, choosing the Appearance Tab in the pop-up dialog, and selecting Scrollbar from the Item drop-down list. On most machines, the size will be the default 18 pixels, but 16 is gaining popularity.

All known operating systems use the same scrollbar for <body> as well as <textarea> elements. The difference in height that the word-wrap setting makes on a textarea therefore holds a vital clue. Toggling the overflow property of the html, documentElement and body elements seems to produce unreliable results in some combinations of browser and operating system, but textareas have been a trustworthy part of html since ancient days. Thanks to css the element does not need to be visible when toggling the wrap setting between hard and soft, although the below example is.

The test form


The code

If conforming to xhtml, a <div> or similar is required as a wrapper for the <textarea> in a form, otherwise the necessary code may remain pretty plain:

<form action="#" id="f">
    <textarea cols="20" rows="2" name="t"></textarea>

The Javascript function then can be just as straightforward: the function does not create any variables in the global scope, it does not rely on advanced dom methods, it does not even need to wait for the window.onload event to fire, it can run as soon as the last end tag above has been read and rendered by the browser. Depending on your plans with the result, a return statement to a calling environment might be more appropriate than the messages as shown.

(function() {
  var a, t = document.forms.f.elements.t;
  t.wrap = 'off'; a = t.offsetHeight;
  t.wrap = 'soft'; a -= t.offsetHeight;
  t.value = a ?
   'Your scrollbars are ' + a + ' pixels wide.' :
   'Sorry, this browser doesn\'t cooperate.';

In IE and Mozilla environments, an even simpler solution exits. There a div styled with overflow: scroll and no content, can be used in a similar fashion. The offsetWidth of the element will be a scrollbar wider than the clientWidth, hence the difference between the two holds the desired value.

<div style="overflow: scroll;" id="testdiv"></div>