• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Page Details / Calculate the size of scrollbar

Calculate the size of scrollbar

Calculate the size of scrollbar

1. Subtract clientWidth from offsetWidth

The clientWidth property indicates the width without scrollbar. The offsetWidth, on the other hand, includes the scrollbar if there is.

Here is the simple calculation to determine the width of scrollbar:

const scrollbarWidth = document.body.offsetWidth - document.body.clientWidth;

2. Use a fake element

We create two fake div elements, one of them is the child of the other. Then calculate the difference between their widths.

const calculateScrollbarWidth = function () {
    // Create the parent element
    const outer = document.createElement('div');
    outer.style.visibility = 'hidden';
    outer.style.overflow = 'scroll';

    // Append it to `body`
    document.body.appendChild(outer);

    // Create the child element
    const inner = document.createElement('div');
    outer.appendChild(inner);

    // Calculate the difference between their widths
    const scrollbarWidth = outer.offsetWidth - inner.offsetWidth;

    // Remove the parent element
    document.body.removeChild(outer);

    return scrollbarWidth;
};

This method doesn’t work on macOS if the Show scroll bars option is set as Automatically based on mouse or trackpad or When scrolling.

Source

https://htmldom.dev/calculate-the-size-of-scrollbar/

Page Details

Related Snippets:

  • Redirection: How to Change the URL in JavaScript
  • Get the Width and Height of the Window
  • Get Width and Height of an Element
  • Notify when element size is changed

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers