Categories
JavaScript Answers

How to Check if a Scrollbar is Visible with JavaScript?

Spread the love

Sometimes, we may want to check if a scrollbar is visible in our JavaScript web app.

In this article, we’ll look at how to check if a scrollbar is visible with JavaScript.

Comparing scrollHeight with clientHeight

The HTML element’s scrollHeight property is a read-only property that is a measurement of the height of an element’s content.

It includes the content that’s not visible on the screen due to overflow.

It’s measured in pixels.

The HTML element’s clientHeight property is a read-only property that is zero for elements that have no CSS or inline frame layouts.

And it’s the number of pixels of the inner height including the padding but excluding the borders, margins, and horizontal scrollbars otherwise.

Therefore, we can compare the scrollHeight of an element with its clientHeight to determine whether a scrollbar would be shown.

If scrollHeight is bigger than clientHeight , then we know the scrollbar would be shown since there would be overflow text.

For instance, we can write the following HTML:

<p>
  hello world
</p>

<div style='height: 100px; overflow-y: auto'>

</div>

Then we can write the following JavaScript:

const scrollbarVisible = (element) => {
  return element.scrollHeight > element.clientHeight;
}

const p = document.querySelector('p')
const div = document.querySelector('div')

for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.textContent = i
  div.appendChild(p)
}

console.log(scrollbarVisible(p))
console.log(scrollbarVisible(div))

We create the scrollbarVisible function to return the result of comparing the element ‘s scrollHeight with its clientHeight .

Then we get the p and div elements with document.querySelector .

Next, we have a for loop to create p elements and append them as child elements of the div.

Since we set the height of the div to 100px and overflow-y is set to auto , we can scroll through the content we added.

Then finally, we log the returned result of the scrollbarVisible function on the p and div elements.

Then first console log should log false since there’s no overflowing content.

And the 2nd console log should log true since there is overflowing content.

Conclusion

To check if a scrollbar is present for an element, we can compare the scrollHeight value with its clientHeight value, both are in pixels.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *