# All files / src/scroll getScrollbarWidth.ts

93.75% Statements 30/32
80% Branches 4/5
100% Functions 1/1
93.75% Lines 30/32

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    331x
    1x
    1x
    1x
    1x
    1x
    24x
    24x

    24x
    24x
    24x
    19x
    19x
    5x
    5x
    5x
    5x
    5x
    5x
    5x
    5x
    5x
    5x
    5x
    5x
    5x
    5x
    5x
    5x
    5x
     let cache: number | undefined;

    /**
     * @internal
     */
    export function getScrollbarWidth(force = false): number {
      /* istanbul ignore if */
      if (typeof window === "undefined") {
        return 0;
      }

      let value = cache;
      if (!force && typeof value === "number") {
        return value;
      }

      const outer = document.createElement("div");
      outer.style.visibility = "hidden";
      outer.style.overflow = "scroll";
      document.body.appendChild(outer);

      const inner = document.createElement("div");
      outer.appendChild(inner);

      // the scrollbar width can be determined by comparing the width of the parent
      // element that has scrollbars to the child element that does not.
      value = outer.offsetWidth - inner.offsetWidth;
      cache = value;
      document.body.removeChild(outer);

      return value;
    }