0

In my page, I wish to detect whether the page has vertical scrollbars, and if so, need to detect the width of the scrollbar, so I can reduce my body by the width and thus prevent my sidebar from changing location from viewing a non-scrolling page to a scrolling page. I have the following jQuery/Javascript code:

        $(document).ready(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();
        }

        if ($("body").height() > $(window).height()) {
            //change width of body here
        }
    });

Unfortunately, this code doesn't work for me. Can someone please let me know where I'm going wrong?

Andre C
  • 457
  • 1
  • 9
  • 26

2 Answers2

0
(function($) {
    $.fn.ScrollBarWidth = function() {
        if (this.get(0).scrollHeight > this.height()) { //check if element has scrollbar
            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);
        }
    }
})(jQuery);

Runs like so :

var scrollbarWidth = $('body').ScrollBarWidth();
console.log(scrollbarWidth);​ //prints the scrollbar width to the console

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
0

You shouldn't need to change the width of the body. By default, it's 100% of the window's width and will adjust when scrollbars appear.

However, if you can't for some reason set the width to 100%, first see if disabling the horizontal scrollbar helps you:

overflow-x: hidden;

If that doesn't cut it, use the function from here to get the scrollbar's width. Then, listen to the window resize event:

var $window = $(window),
    $body = $('body');

function resize() {
    if ($body.height() > $window.height()) {
        $body.width($body.width() - getScrollBarWidth());
    }
}

$(window).resize(resize);​
Community
  • 1
  • 1
Brian Ustas
  • 62,713
  • 3
  • 28
  • 21