14

How can I get the browser scrollbar height? Does JS have a built-in function for this case? Somebody please help me out of this.

user3828771
  • 1,603
  • 3
  • 14
  • 14

3 Answers3

16

There isn't a built-in method for this. However, the scrollbar's height is supposed to give an indication of how much of the available content fits within the available viewport. Going by that, we can determine it like:

var sbHeight = window.innerHeight * (window.innerHeight / document.body.offsetHeight);

Where window.innerHeight / document.body.offsetHeight is the percentage of content visible currently. We multiple that with the available viewport height to get the approximate scrollbar height.

Note: Different browsers may add/reduce some pixels to/from the scrolbar height.

techfoobar
  • 65,616
  • 14
  • 114
  • 135
  • 2
    I suppose there is a mistake here. For example, I've got a window with innerHeight = 500 and body.offsetHeight = 2000 so I get scrollbar's height = 500 * (500 / 2000) = 125 px. And if body.offsetHeight = 100 than I get scrollbar's height = 2500. It is too much for a scrollbar, isn't it? – SergeyT Sep 07 '18 at 13:08
  • isn't it supposed to be scrollHeight to get the percentage visible ? – Tirterra Jan 22 '23 at 14:14
4
'window.pageYOffset'

returns the current height of the scrollbar concerning the full height of the document. A simple example of usage is like

alert('Current scroll from the top: ' + window.pageYOffset)
-5

Does this help?

this.document.body.scrollHeight
alansiqueira27
  • 8,129
  • 15
  • 67
  • 111