Determing the dimensions of the browser's scroll bar

I have come across a query regarding the calculation of browser scrollbar sizes. However, my focus is on understanding how the solution in the npm package called scrollbar-wdith actually works. Can someone provide an explanation for this?

To give some context, here is the relevant code written in (.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

  scrollbarWidth

Answer №1

I made some adjustments to the code by simplifying the core concept.

<html>
<head>
</head>
<body>
</body>
<script>
  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';
    document.body.appendChild(div1);
    document.body.appendChild(div2);
    scrollbarWidth = Math.abs(div1.scrollHeight - div2.scrollHeight);
    alert(scrollbarWidth);
    return scrollbarWidth;
  };

  getScrollbarWidth();

</script>
<html>

By creating two identical divs with and without a scrollbar, the script then calculates their scrollHeight property values to determine the scrollbar's height. This information can be found at http://www.w3schools.com/jsref/prop_element_scrollheight.asp.

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

The difference between the scrollHeights provides the vertical scrollbar's actual height. For example, if div2 has a scrollHeight of 100px (=height) while div1 only measures 83px, Chrome displays a scrollbar with a height of 17px.

Feel free to ask if you need further clarification.

Answer №2

Check out this concise snippet that also utilizes a CSS custom property, --scrollbar, to set the pixel size of the scrollbar (if your browser is compliant with the specification):

(function(elem, body){
  elem.style.display = 'inline-block';
  elem.style.position = 'absolute';
  elem.style.height = '0';
  elem.style.overflow = 'scroll';
  body.appendChild(elem);
  body.style.setProperty('--scrollbar', elem.offsetWidth + 'px');
  body.removeChild(elem);
})(document.createElement('scrollbartester'), document.body);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Supplier for a module relying on data received from the server

My current component relies on "MAT_DATE_FORMATS", but I am encountering an issue where the "useValue" needs to be retrieved from the server. Is there a way to make the provider asynchronous in this case? export const MY_FORMATS = { parse: { d ...

Utilizing JSONP in Google Chrome for JavaScript

I came across a code snippet that I found here: After testing it on Firefox with two different domains, everything worked perfectly. However, when I attempted to run it on Google Chrome, I encountered the following warning: Resource interpreted as Scri ...

List the attributes that have different values

One of the functions I currently have incorporates lodash to compare two objects and determine if they are identical. private checkForChanges(): boolean { if (_.isEqual(this.definitionDetails, this.originalDetails) === true) { return false; ...

Utilizing React Router V4 to Render Dual Components on a Single Route

Looking for help with these routes <Route exact path={`/admin/caters/:id`} component={Cater} /> <Route exact path={'/admin/caters/create'} component={CreateCater} /> After visiting the first route, I see a cater with an ID display ...

If I click on the datalist link option during an ajax append, I would like to be redirected

When I try to link after clicking an option in the appended AJAX, it does not seem to work as expected: More details: $('#input-friends').on('input', function () { var id = $('#input-friends').val(); $.ajax({ ...

Receiving a response from xmlHttpRequest that leaves me uncertain

I have been working on a new code snippet to seamlessly add data to a database using ajax. Here's the HTML structure: <form> Product Name:</br> <input type=text name=productName id="addProductName"></br> ...

removing an item from a nested array through the use of the filter() method

I have been struggling to remove an element with a specific ID from a nested array. Are there any suggestions on how to effectively utilize the filter() method with nested arrays? The goal is to only eliminate the object with {id: 111,name: "A"}. Below ...

Using a semicolon right after "id" is recognized as an unexpected token

I encountered an issue while attempting to run my express.js program. The main server fails to start and displays the following error message. id; ^ SyntaxError: Unexpected token ; at new Script (vm.js:80:7) at createScript (vm.js:274:10) ...

Are there any tools available for selecting fonts to use in an input form for users?

I am currently seeking a font picker tool that can be integrated into my web project to allow users to select from a variety of fonts. I have implemented a basic code using radio buttons, which seems to be functioning as intended: <label style="font-fa ...

To ensure the next line only runs after the line above has finished executing, remember that the function is invoked in HTML

my.component.html <button (click)="refresh()">Refresh</button> my.component.ts refresh() { let self = this; self.isRefresh = true; //1st time self.getfun().then(() => { self.isRefresh = false; ...

Filtering an array of map/key pairs can be done by using various methods to

I am searching for individuals above the age of 21. const people = [ {0: {name: 'john', age: 30}}, {1: {name: 'jay', age: 33}}, {2: {name: 'cris', age: 18}} ]; The code snippet provided below did not produce an ...

Update the content of the widget

Currently, I am utilizing the following script to display NBA standings: <script type="text/javascript" src="https://widgets.sports-reference.com/wg.fcgi?script=bbr_standings&amp;params=bbr_standings_conf:E,bbr_standings_css:1&amp"></sc ...

Struggling to implement a JavaScript dynamic menu on an HTML website and encountering persistent difficulties

Alright, let's take a look at the HTML code I've put together: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Menus</title> <script type="text/javascript" src="Cities.js"> </scr ...

What is the best way to specify the data type as double for the onChange Event

I am currently utilizing React's onChange event in an input tag and have encountered an issue with type definitions. Take a look at this code: onChange?: (e: ChangeEvent<HTMLInputElement> | SeperationChangeEvent) => void; This is how I&ap ...

Preventing Image Blocking - Efficiently Loading Pages to Avoid Slow Loading (Image Queueing)

The page seems to be loading slower than anticipated. Upon checking the timeline using firebug, it appears that there are significant image blocking instances: https://i.sstatic.net/T5aG5.png I suspect an error in my approach (I am aware of the duplicate ...

JavaScript: Creating an array of images from a directory

I've encountered a problem that has proven to be more complex than expected - I am struggling to find resources related to my specific question. My goal is to store 36 images from a folder on my computer into an array using Javascript. Below, you will ...

Is there a way to have the collapsible content automatically expanded upon loading?

I came across a tutorial on w3school (https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_collapsible_symbol), which demonstrates collapsible content hidden by default. The code snippet from the link is provided below. Can someone assist me in cha ...

Dealing with Lengthy Requests: Effective Strategies

My ajax request sometimes takes a while to return a response. $.ajax({ type: 'POST', url: 'some_url', data: data, processData: false, contentType: false, headers: { "Authorization": 'Token token="&a ...

The functionality of OnPress for React Native Google Places Autocomplete is hindered by its surrounding parent components

I'm currently implementing the react-native-google-places-autocomplete library in my React Native application. However, I've encountered an issue when trying to select an address from the suggested list provided by Google. Whenever I click on a s ...

Encountering compilation issues with Jest in Vue project, yet the tests are successfully passing

I'm currently facing an issue with my module building while using jest with vue.js for testing. The tests are running successfully, but the module building is failing unexpectedly. I have provided my code snippet below and would greatly appreciate any ...