How can I determine the height of a horizontal scrollbar, or the width of a vertical one, in JavaScript?
Create an empty div
and make sure it's present on all pages (i.e. by putting it in the header
template).
Give it this styling:
#scrollbar-helper {
// Hide it beyond the borders of the browser
position: absolute;
top: -100%;
// Make sure the scrollbar is always visible
overflow: scroll;
}
Then simply check for the size of #scrollbar-helper
with Javascript:
var scrollbarWidth = document.getElementById('scrollbar-helper').offsetWidth;
var scrollbarHeight = document.getElementById('scrollbar-helper').offsetHeight;
No need to calculate anything, as this div
will always have the width
and height
of the scrollbar
.
The only downside is that there will be an empty div
in your templates.. But on the other hand, your Javascript files will be cleaner, as this only takes 1 or 2 lines of code.
detectScrollbarWidthHeight: function() {
var div = document.createElement("div");
div.style.overflow = "scroll";
div.style.visibility = "hidden";
div.style.position = 'absolute';
div.style.width = '100px';
div.style.height = '100px';
document.body.appendChild(div);
return {
width: div.offsetWidth - div.clientWidth,
height: div.offsetHeight - div.clientHeight
};
},
Tested in Chrome, FF, IE8, IE11.
You can determine window
scroll bar with document
as below using jquery + javascript:
var scrollbarWidth = ($(document).width() - window.innerWidth);
console.info("Window Scroll Bar Width=" + scrollbarWidth );
It seems to work, but maybe there is a simpler solution that works in all browsers?
// 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;
}
If you already have an element with scrollbars on it use:
function getScrollbarHeight(el) {
return el.getBoundingClientRect().height - el.scrollHeight;
};
If there is no horzintscrollbar present the function will retun 0
With jquery (only tested in firefox):
function getScrollBarHeight() {
var jTest = $('<div style="display:none;width:50px;overflow: scroll"><div style="width:100px;"><br /><br /></div></div>');
$('body').append(jTest);
var h = jTest.innerHeight();
jTest.css({
overflow: 'auto',
width: '200px'
});
var h2 = jTest.innerHeight();
return h - h2;
}
function getScrollBarWidth() {
var jTest = $('<div style="display:none;height:50px;overflow: scroll"><div style="height:100px;"></div></div>');
$('body').append(jTest);
var w = jTest.innerWidth();
jTest.css({
overflow: 'auto',
height: '200px'
});
var w2 = jTest.innerWidth();
return w - w2;
}
But I actually like @Steve's answer better.