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.
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();
Setting a div's overflow to "scroll
" automatically adds scrollbars
(even if there's nothing inside, the scrollbars
will be there, but grey). So just make a div, find the width, set overflow to scroll, and find the new width, and return the difference:
function getScrollBarWidth() {
var helper = document.createElement('div');
helper.style = "width: 100px; height: 100px; overflow:hidden;"
document.body.appendChild(helper);
var bigger = helper.clientWidth;
helper.style.overflow = "scroll";
var smaller = helper.clientWidth;
document.body.removeChild(helper);
return(bigger - smaller);
}
try this
$("#myDiv")[0].scrollWidth
Here is a plain javascript version that is way faster.
function getScrollbarWidth() {
var div, body, W = window.browserScrollbarWidth;
if (W === undefined) {
body = document.body, div = document.createElement('div');
div.innerHTML = '<div style="width: 50px; height: 50px; position: absolute; left: -100px; top: -100px; overflow: auto;"><div style="width: 1px; height: 100px;"></div></div>';
div = div.firstChild;
body.appendChild(div);
W = window.browserScrollbarWidth = div.offsetWidth - div.clientWidth;
body.removeChild(div);
}
return W;
};