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.