kalu kalu - 4 months ago 18x
Javascript Question

Computing the browser's scrollbar size

There is another question asking how to calculate the browser's scrollbar sizes.

My question is about the solution implemented in the npm package scrollbar-wdith. Can somebody explain why it works?

For reference, here is the relevant code (.coffee):

scrollbarWidth = null

getScrollbarWidth = (recalculate = false) ->
return scrollbarWidth if scrollbarWidth? and not recalculate

return null if document.readyState is 'loading'

div1 = document.createElement 'div'
div2 = document.createElement 'div'

div1.style.width = div2.style.width = div1.style.height = div2.style.height = '100px'
div1.style.overflow = 'scroll'
div2.style.overflow = 'hidden'

document.body.appendChild div1
document.body.appendChild div2

scrollbarWidth = Math.abs div1.scrollHeight - div2.scrollHeight

document.body.removeChild div1
document.body.removeChild div2



Here's what i did. Took the crux of the code and simplified it a bit.

  var scrollbarWidth;

  scrollbarWidth = null;

  getScrollbarWidth = function(recalculate) {
    var div1, div2;
    div1 = document.createElement('div');
    div2 = document.createElement('div');
    div1.id = "div1";
    div2.id = "div2";
    div1.style.width = div2.style.width = div1.style.height = div2.style.height = '100px';
    div1.style.overflow = 'scroll';
    div2.style.overflow = 'hidden';
    scrollbarWidth = Math.abs(div1.scrollHeight - div2.scrollHeight);
    return scrollbarWidth;



This let me play around with the elements.

what happens is that they create two identical divs, one with a scroll bar and another without a scrollbar and then they query the scrollHeight property for both of them, which ignores the scrollbar (just the element and padding).. see here - http://www.w3schools.com/jsref/prop_element_scrollheight.asp

The scrollHeight property returns the entire height of an element in pixels, including padding, but not the border, scrollbar or margin.

the difference in the scrollHeights yields the required scrollbar's height (since one of the elements has a scrollbar and the other one does not)

as it turns out, div2 scrollHeight = 100 px (=height) while div1's scrollHeight was only 83px and so chrome has a scrollbar of height 17px

Let me know if that makes sense to you