2

I'm trying to figure out the width of the scrollbars of the browser (e.g. Edge, Firefox, Opera, Chrome, etc...) a user might be using (if the scrollbars are present) and added it to the width of the window so that my JQuery code aligns up with my CSS code for when the browser is resized so far I can figure out the width of the window but not the scrollbars.

JQuery

$(window).on('resize',function(){
    if($(this).width() > 680){
        //add remove css styles
    }
});
linkNES
  • 113
  • 1
  • 6

2 Answers2

0

You can use this function to get it:

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);
};

I hope it helps you...

Radames E. Hernandez
  • 4,235
  • 27
  • 37
0

I figured out a way that seems to work for me if anyone has a better solution or can improve this code please let me know.

$(window).on('resize',function(){
    //get accurate width of the screen by removing scrollbars
    $('html, body').css('overflow', 'hidden');
    var w = $(window).width();

    //add back the scrollbars
    $('html, body').css('overflow', 'visible');
    if(w > 680){
        //add more code here what you need done when screen reaches desired size
    }
});
linkNES
  • 113
  • 1
  • 6