Gauranga
Gauranga

Reputation: 19

How to know whether a browser is displaying scrollbar is present or not in reactjs?

I am working on react project. when we make the screen size decrease from large to tiny, a scroll bar is appearing in the browser and as a result my testcases are failing.I wanted to know is there any way we can find whether a scroll bar is displayed in the browser for all types of screen sizes. Also is there any way to get the size of the scroll bar being displayed in the browser?

Upvotes: 0

Views: 1371

Answers (3)

Pavel Kratochvil
Pavel Kratochvil

Reputation: 481

In this sandbox I have tested two posible solutions. First approach (ScrollableComponent and hook useIsScrollable) is based on trying to scroll with element. If it does something then you know that it has scrollbar. The second aproach is based on measuring (ScrollableComponentA and hook useIsScrollableA). Measure wrapper element and inner element and compare its height and width.

Upvotes: 0

Andrew
Andrew

Reputation: 111

You can compare the height of your content with the height of the window. So if (document.body.offsetHeight > window.innerHeight) then the scrollbar would be visible.

UPD: Regarding scrollbar's sizes. Its width is just a difference between window.innerWidth and document.body.offsetWidth, and its height is equal to window.innerHeight. So summing up:

let scrollbarSize = {
  heigth: window.innerHeight,
  width: window.innerWidth - document.body.offsetWidth
}

Upvotes: 1

Tolumide
Tolumide

Reputation: 984

I would have preferred a comment but I do not have access to that yet.

I am assuming you are talking about height here if not please apply the same solutionwhere appropriate.

To know whether your browser is displaying the vertical scrollbar. Compare the height of the document and the screen height.

Method for the calculation of document height would usually vary across browsers in this case. Use something like this:

let scrollHeight = Math.max(
  document.body.scrollHeight, document.documentElement.scrollHeight,
  document.body.offsetHeight, document.documentElement.offsetHeight,
  document.body.clientHeight, document.documentElement.clientHeight
);

To calculate your window height use:

const windowHeight = documentElement.clientHeight

If your scrollHeight is greater than the windowHeight then you can be most certain that the vertical scrollbar is present. Therefore it would be easy to detect

Upvotes: 0

Related Questions