Search code examples
javascripthtmlwidthscrollbar

How to calculate the width of the scroll bar?


Given a <textarea> with a fixed width, I would like its "active width" to be constant (in px). By "active width" I mean the area where the text appears.

When the vertical scroll bar doesn't appear, the "active width" equals to width. But, when the vertical scroll bar appears, the "active width" becomes smaller than width (I guess smaller exactly by the width of the scroll bar).

I thought to identify whether the vertical scroll bar appears or not, and if yes, to increase the width of the <textarea> by the width of the scroll bar. How could I identify the width of the scroll bar?

Is there a better approach?

(I'm interested in Firefox, if it makes the life easier.)


Solution

  • There is a jQuery plugin that can help with this: https://github.com/brandonaaron/jquery-getscrollbarwidth/blob/master/jquery.getscrollbarwidth.js

    Also, from http://www.alexandre-gomes.com/?p=115 Here is some code that may help.

    This creates a hidden <p> element at 100% width inside a <div> with a scrollbar, then calculates the <div> width - the <p> width = scroll bar 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); 
    };