max
max

Reputation: 640

Window width and scroll width values

I want to show "back-to-top" button when the screen resolution is bigger or equal 1200px. Of course, it depends on window width. Here is jQuery code:

    var wW = $(window).width() + 17;
console.log(wW);
            if (wW >= 1200) {
                $(window).scroll(function () {
                    if ($(this).scrollTop() > 100) {
                        $('#oc-ontop').fadeIn('fast');
                    } else {
                        $('#oc-ontop').fadeOut('fast');
                    }
                });
            }

So, if you set the window width to 1200px, console show you the value 1200. But 1200 is the sum of window width (1183px) + scrollbar width (17px). How can I calculate scrollbar width in this function to be independent of it's width?

Upvotes: 0

Views: 1071

Answers (1)

RodrigoDela
RodrigoDela

Reputation: 1736

Take a look at this thread: How can I get the browser's scrollbar sizes?

When you apply the code from there (originally Alexandre Gomes Blog):

function getScrollBarWidth () {
  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);
};

You can write:

var wW = $(window).width() + getScrollBarWidth();

Upvotes: 1

Related Questions