Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scrollHeight property in FireFox

I'm working on a function to detect whether text inside of a DIV element would overflow. In this regard I have a function working in both Chrome and IE that compares the element's scrollHeight to the clientHeight attributes.

However in FireFox both attributes (as well as offsetHeight) always report the same number which happens to be the height of the div element.

I do get accurate results from the scrollHeight property if I add 'overflow:auto' to the div style. But displaying the scrollbar isn't an acceptable solution for the project I'm working on.

Any suggestions?

like image 599
Linus Avatar asked Dec 06 '10 19:12

Linus


People also ask

What is scrollHeight property?

The scrollHeight property returns the height of an element including padding, but excluding borders, scrollbars, or margins. The scrollHeight property returns the height in pixels. The scrollHeight property is read-only.

How do you get scrollHeight?

To get the height of the scroll bar the offsetHeight of div is subtracted from the clientHeight of div. OffsetHeight = Height of an element + Scrollbar Height. ClientHeight = Height of an element. Height of scrollbar = offsetHeight – clientHeight.

What is scrollTop and scrollHeight?

In summary, scrollTop is how much it's currently scrolled, and scrollHeight is the total height, including content scrolled out of view.

Why is clientHeight and scrollHeight the same?

If the element's content can fit without a need for vertical scrollbar, its scrollHeight is equal to clientHeight.


2 Answers

That's documented behaviour:

When an element's content does not generate a vertical scrollbar, then its scrollHeight property is equal to its clientHeight property.

https://developer.mozilla.org/en/DOM/element.scrollHeight


I know that it isn't clean, but could you do something like this?

e.style.overflow = "scroll";
var scrollHeight = e.scrollHeight;
e.style.overflow = "hidden";

The user can't see that because the page only gets redrawn when no javascript is currently running.

like image 55
thejh Avatar answered Oct 13 '22 00:10

thejh


Kartikaya Gupta explains Firefox's behavior in a blog post on the scrollWidth/scrollHeight properties.

The recommendation to detect if an element would overflow is to make it scrollable and set scrollLeft/scrollTop to 1 temporarily. When at least scrollWidth or scrollHeight keeps its value then the element would overflow.
In order to prevent the check being visible to the user, you might want to perform the check in a cloned element that is placed in the negative top or left of the viewport.

like image 29
Augustus Kling Avatar answered Oct 12 '22 22:10

Augustus Kling