April 1, 2012
Scrollable Textarea Without Scrollbar
I hate scrollbars in textareas. I needed a message form for my new website and the scrollbar was sticking out of my design like a sore thumb.
When searching through forums I was only able to find solutions with overflow:hidden. The problem is that overflow:hidden disables scrolling and when your message is longer than the textarea you cannot scroll to the end of your text and you cannot see what you are typing.
Some people proposed stuff like using JavaScript to fake scrolling by capturing keystrokes and repositioning the container element... but that just seemed ugly and none of those scripts worked really well.
I came up with another solution. We can wrap the textarea into a wrapper div.
<div id="wrapper">
<textarea id="textarea" rows="5" cols="45"></textarea>
</div>
Now we can give the wrapper overflow:hidden and set it's width a bit narrower than the width of the textarea so that scrollbar would be hidden...and we are done, right? It's not that simple - different browsers use different width of scrollbar so we don't know how many pixels narrower should the width of our wrapper be. So let's just use the same width for the wrapper for now.
#textarea {
width: 335px;
border: none;
}
#wrapper {
width: 335px;
border: 1px solid gray;
overflow: hidden;
}
Now we use JavaScript to detect the width of the inner part of our textarea...
// get the width of the textarea minus scrollbar
var textareaWidth = document.getElementById("textarea").scrollWidth;
...and we set the width of our wrapper to the detected number of pixels.
// width of our wrapper equals width of the inner part of the textarea
document.getElementById("wrapper").style.width = textareaWidth + "px";
We also need to make sure that the hidden scrollbar is always there... so we just use overflow-y:scroll for our textarea.
#textarea {
border: none;
overflow-y: scroll;
width: 335px;
}
And that's all. You can try demo if you want. Simple, huh? As far as I know it works in every browser - if not, please let me know.