Internet Explorer TextArea scrollHeight Bug
While working with some dynamically created textarea tags, I noticed some odd behavior in Internet Explorer. I was trying to get a textarea tag to fit to the height of its content, while allowing a horizontal scrollbar for when a word (or url) is too long for the available width.
Here is the function I came up with:
function fitTextToHeight(textarea){
// get rid of scrollbars to get accurate height
textarea.style.overflow = 'hidden';
// set height to available scroll height
textarea.style.height = textarea.scrollHeight + 'px';
// allow horizontal scrolling if words are too long
textarea.style.overflowX = 'auto';
// keep the vertical scrollbar hidden, as it's no longer needed
textarea.style.overflowY = 'hidden';
}
This function works great for all browsers that I tested (Firefox, Chrome, Safari, Opera) except Internet Explorer. I tested it a bit further, to see how far back this bug goes, and I was able to reproduce it in IE6 through IE8 (At the time of this article v8.0.6001.18702). IE 5.5 behaved as the other browsers did.
To work around this issue, I noticed that just making a dummy statement for scrollHeight, makes it behave as expected. Work around shown below:
function fitTextToHeight(textarea){
// get rid of scrollbars to get accurate height
textarea.style.overflow = 'hidden';
// Internet Explorer 6-8 needs this to get the correct value
textarea.scrollHeight;
// set height to available scroll height
textarea.style.height = textarea.scrollHeight + 'px';
// allow horizontal scrolling if words are too long
textarea.style.overflowX = 'auto';
// keep the vertical scrollbar hidden, as it's no longer needed
textarea.style.overflowY = 'hidden';
}
Here’s a demo: Internet Explorer TextArea scrollHeight Bug Demo
One other thing that I noticed, is that you can put an alert right before using the scrollHeight property, and it works fine. So this is not necessarily just tied to accessing the scrollHeight property, it may have something to do with execution time.