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
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.
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 .
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.
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.
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:
hidden
auto
(to get scrollbars)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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With