From Alexandre Gomes Blog I have not tried it. Let me know if it works for you.
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);
};
Using jQuery, you can shorten Matthew Vines answer to:
function getScrollBarWidth () {
var $outer = $('<div>').css({visibility: 'hidden', width: 100, overflow: 'scroll'}).appendTo('body'),
widthWithScroll = $('<div>').css({width: '100%'}).appendTo($outer).outerWidth();
$outer.remove();
return 100 - widthWithScroll;
};
if you are looking for a simple operation, just mix plain dom js and jquery,
var swidth=(window.innerWidth-$(window).width());
returns the size of current page scrollbar. (if it is visible or else will return 0)
This is only script I've found, which is working in webkit browsers ... :)
$.scrollbarWidth = function() {
var parent, child, width;
if(width===undefined) {
parent = $('<div style="width:50px;height:50px;overflow:auto"><div/></div>').appendTo('body');
child=parent.children();
width=child.innerWidth()-child.height(99).innerWidth();
parent.remove();
}
return width;
};
Minimized version:
$.scrollbarWidth=function(){var a,b,c;if(c===undefined){a=$('<div style="width:50px;height:50px;overflow:auto"><div/></div>').appendTo('body');b=a.children();c=b.innerWidth()-b.height(99).innerWidth();a.remove()}return c};
And you have to call it when document is ready ... so
$(function(){ console.log($.scrollbarWidth()); });
Tested 2012-03-28 on Windows 7 in latest FF, Chrome, IE & Safari and 100% working.
source: http://benalman.com/projects/jquery-misc-plugins/#scrollbarwidth
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