How can I determine the height of a horizontal scrollbar, or the width of a vertical one, in JavaScript?
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)
I found a simple solution that works for elements inside of the page, instead of the page itself:
$('#element')[0].offsetHeight - $('#element')[0].clientHeight
This returns the height of the x-axis scrollbar.
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
This should do the trick, no?
function getScrollbarWidth() {
return (window.innerWidth - document.documentElement.clientWidth);
}
From David Walsh's blog:
// Create the measurement node
var scrollDiv = document.createElement("div");
scrollDiv.className = "scrollbar-measure";
document.body.appendChild(scrollDiv);
// Get the scrollbar width
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
console.info(scrollbarWidth); // Mac: 15
// Delete the DIV
document.body.removeChild(scrollDiv);
.scrollbar-measure {
width: 100px;
height: 100px;
overflow: scroll;
position: absolute;
top: -9999px;
}
Gives me 17 on my website, 14 here on Stackoverflow.