Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

div scrollbar width

Is there an easy way to get the width of a scrollbar using javascript / jquery ? I need to get the width of a div that overflows + whatever width the scroll bar is.

Thank you

like image 755
G-Man Avatar asked Sep 21 '11 14:09

G-Man


People also ask

How do I change the scrollbar width?

The scrollbar-width property is used to set the width or thickness of an element's scrollbar when shown. This property can be used on pages where the user interface requires the element to be displayed more prominently and shrinking the scrollbar width gives more space to the element.

What is the width of scrollbar?

For Windows it usually varies between 12px and 20px . If the browser doesn't reserve any space for it (the scrollbar is half-translucent over the text, also happens), then it may be 0px .

How can I get the width of my scroll bar?

To get the width of the scrollbar, you use the offsetWidth and clientWidth of the Element : The offsetWidth returns the width of the Element in pixels including the scrollbar. The clientWidth returns the with of the Element in pixels without the scrollbar.

How do I reduce the scrollbar width in HTML?

scrollbar-width accepts the following values: auto is the default value and will render the standard scrollbars for the user agent. thin will tell the user agent to use thinner scrollbars, when applicable. none will hide the scrollbar completely, without affecting the element's scrollability.


1 Answers

if you're using jquery, try this:

function getScrollbarWidth() 
{
    var div = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div></div>'); 
    $('body').append(div); 
    var w1 = $('div', div).innerWidth(); 
    div.css('overflow-y', 'auto'); 
    var w2 = $('div', div).innerWidth(); 
    $(div).remove(); 
    return (w1 - w2);
}

i'm using this in the project i'm working on and it works like a charm. it gets the scrollbar-width by:

  1. appending a div with overflowing content to the body (in a non-visible area, -200px to top/left)
  2. set overflow to hidden
  3. get the width
  4. set overflow to auto (to get scrollbars)
  5. get the width
  6. substract both widths to get width of the scrollbar

so what you'll have to do is getting the width of your div ($('#mydiv').width()) and add the scrollbar-width:

var completewidth = $('#mydiv').width() + getScrollbarWidth();
like image 82
oezi Avatar answered Oct 14 '22 23:10

oezi