Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting the same value for clientWidth and offsetWidth when scrollbars are present?

Tags:

javascript

css

https://javascript.info/task/scrollbar-width This is one of the most frustrating issues I have had yet. The link provided shows how to get the scrollbar width by subtracting the clientWidth from the offsetWidth. Yet I get the same width for both! I have tried firefox and chrome. The browser is not zoomed in. Scrollbars are present. I tried it in another project and got the same result. Please tell me what I am missing.

$(".searchEvents").click(function(){
    var div = document.querySelector('.main-container');
//        let scrollWidth = div.offsetWidth - div.clientWidth;

        alert(div.offsetWidth);
        alert(div.clientWidth);
           });   
like image 511
jmoney Avatar asked Dec 09 '25 01:12

jmoney


1 Answers

Try this.

JsFiddle link : Click me

function getScrollbarWidth() {

  // Creating invisible container
  const outer = document.createElement('div');
  outer.style.visibility = 'hidden';
  outer.style.overflow = 'scroll'; // forcing scrollbar to appear
  outer.style.msOverflowStyle = 'scrollbar'; // needed for WinJS apps
  document.body.appendChild(outer);

  // Creating inner element and placing it in the container
  const inner = document.createElement('div');
  outer.appendChild(inner);
  
  // Calculating difference between container's full width and the child width
  const scrollbarWidth = (outer.offsetWidth - inner.offsetWidth);

  // Removing temporary elements from the DOM
  outer.parentNode.removeChild(outer);

  return scrollbarWidth;
    
}

document.body.innerHTML = 'Scrollbar width is: ' + getScrollbarWidth() + 'px';
like image 60
Pushprajsinh Chudasama Avatar answered Dec 10 '25 13:12

Pushprajsinh Chudasama



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!