Oh, <textarea>
‘s. How many quirks you posses. Here is a collection of nine things you might want to do related to textareas. Enjoy.
1. Image as textarea background, disappears when text is entered.
You can add a background-image to a textarea like you can any other element. In this case, the image is a friendly reminder to be nice =). If you add a background image, for whatever reason, it can break the browser default styling of the textarea. The default 1px solid bolder is replaced with a thicker beveled border. To restore the browser default, you can just force the border back to normal.
textarea {
background: url(images/benice.png) center center no-repeat; /* This ruins default border */
border: 1px solid #888;
}
That background image might interfere with the readability of the text once the text reaches that far. Here is some jQuery that will remove the background when the textarea is in focus, and put it back if the textarea is left without any text inside.
$('textarea')
.focus(function() { $(this).css("background", "none") })
.blur(function() { if ($(this)[0].value == '') { $(this).css("background", "url(images/benice.png) center center no-repeat") } });
2. HTML5 placeholder text
There is a new attribute as part of HTML5 forms called placeholder. It shows faded gray text in the textarea (also works for text-style inputs) which disappears when the textarea is in focus or has any value.
<textarea placeholder="Remember, be nice!" cols="30" rows="5"></textarea>
HTML5 placeholder text works in Safari 5, Mobile Safari, Chrome 6, and the Firefox 4 alpha.
3. Placeholder text, HTML5 with jQuery fallback
We can easily test if a particular element supports a particular attribute by testing with JavaScript:
function elementSupportsAttribute(element, attribute) {
var test = document.createElement(element);
if (attribute in test) {
return true;
} else {
return false;
}
};
Then we can write code so that if the browser does support the placeholder attribute, we’ll use that, if not, we’ll mimic the behavior with jQuery:
if (!elementSupportsAttribute('textarea', 'placeholder')) {
// Fallback for browsers that don't support HTML5 placeholder attribute
$("#example-three")
.data("originalText", $("#example-three").text())
.css("color", "#999")
.focus(function() {
var $el = $(this);
if (this.value == $el.data("originalText")) {
this.value = "";
}
})
.blur(function() {
if (this.value == "") {
this.value = $(this).data("originalText");
}
});
} else {
// Browser does support HTML5 placeholder attribute, so use it.
$("#example-three")
.attr("placeholder", $("#example-three").text())
.text("");
}
4. Remove the blue glow
All WebKit browsers, Firefox 3.6, and Opera 10 all put a glowing blue border around textareas when they are in focus. You can remove it from the WebKit browsers like this:
textarea {
outline: none;
}
You could apply it to the :focus style as well, but it works either way. I have not yet found a way to remove it from either Firefox or Opera, but -moz-outline-style was about as far as I tested.
REMINDER: The blue glow is becoming a strong standard and breaking that standard is typically a bad thing for your users. If you do it, you should have a darn compelling reason to as well as a similarly strong :focus style.
5. Remove resize handle
WebKit browsers attached a little UI element to the bottom right of text areas that users can use to click-and-drag to resize a textarea. If for whatever reason you want to remove that, CSS is all it takes:
textarea {
resize: none;
}
6. Add resize handle
jQuery UI has a resizeable interaction that can be used on textareas. It works in all browsers and overrides the WebKit native version, because this version has all kinds of fancy stuff (like callbacks and animation).
To use it, load jQuery and jQuery UI on your page and at its most basic level you call it like this:
$("textarea").resizable();
7. Auto-resize to fit content
James Padolsey has a super nice jQuery script for auto resizing textareas (That’s gone off and on the internet, so here’s a backup.)
Here’s another by Louis Lazeris, which also includes links to other options. It works just how you likely hope it does. The textarea starts out a normal reasonable size. As you type more and more content, the textarea expands to include all of that text, rather than triggering a scrollbar as is the default.
The plugin has a variety of options, but at its simplest you just load jQuery, the plugin file, and call it like this:
$('textarea').autoResize();
Another trick here is to not use a <textarea>
at all, but <div contenteditable>
. That will grow automatically with no fancy JavaScript help at all – except that it’s not a real form element anymore so you’ll need JavaScript to extract/send the value.
8. Nowrap
To prevent text from wrapping normally in CSS, you use #whatever { white-space: nowrap; }. But for whatever reason, that doesn’t work with textareas. If you want to be able to type into textareas and would rather lines do not break until you press return/enter (a horizontal scrollbar is triggered instead), you’ll have to use the wrap="off" attribute.
<textarea wrap="off" cols="30" rows="5"></textarea>
9. Remove default scrollbars in Internet Explorer
IE puts a vertical scrollbar by default on all textareas. You can hide it with overflow: hidden, but then you don’t get any scrollbars at all when you expand. Thankfully auto overflow works to remove the scrollbar but still put them back when needed.
textarea {
overflow: auto;
}
All the above examples can be seen here.
This is one of the most informative posts Chris. I really wanted to know more about text areas and this is one of those rare posts which is solely dedicated to them :D Thanks a ton.
Very, very, useful tips! Thanks! (That’s 3 very’s)
Whoops… very.
Your awesome Chris… thanks.
Good stuff to know!
I think that using jQuery for the textarea is not necessary. I’d rather use CSS pseudo-classes (Hover, active, focus…).
Anything that jQuery was used for in this article was specifically for something that CSS can’t do by itself.
You tell him ! haha
You could do the same thing with :focus, what are you talking about “css can’t do by itself”.
Test it be my guest.
.text {background-color:#FFF;color:#000;}
.text:focus {background-color:#000;color:#FFF;}
The background image stays removed if there is text within the textarea. That text-test can only be performed with JavaScript.
Hm… although I admit it’s not cross-browser, but there is *:empty, right ?
js is used to determine if there’s text or not inside when the focus leaves the textarea, and returns the background only if the textarea has no text.
:empty, not crossbrowser thought.
Wonderful article, I find it very helpful. Great information, and detail!
For #4, I think that’s actually an accessibility issue for people tabbing though a form, same thing with dotted lines around links.
But it’s OK as long as you add a :focus behavior
Woow, all in once tip, thanks Chris
Good stuff Chris, but just one thing: Firefox 3.6 doesn’t put any blue glow on textareas when in focus. I’d also like to point out that for your first example, it’s good to give a CSS fallback with the :focus pseudo-class.
Other than that I will definitely be using some of these in the future, especially the auto-resize.
On my Mac version it does, maybe that’s a Mac-only thing?
Chrome on Windows puts a yelloworange glow around the textbox
Well, at least your comment text box doesnt get a yellow orange glow on Chrome (Windows). I guess you are using these tricks on css tricks too ^^
Yeah, it’s mac-only thing. Other OS have differents default ways to show which element is focused.
The Blue-ish glow is Safari only :)
As Sumeet says though, other browsers do different things, some other like chrome do use a different glow.
Glowing in chrome is down to the theme in use I belive as well ;-)
this changes on every theme-platform because xul tries to use system style for inputs
Already discovered about half of this tricks by myself the hard way, but it’s always good to learn these little things that can make a difference for the user.
Thanks for all these resources Chris!
Check out my contact form
http://bit.ly/b6GSWE
It’s pretty.
That lacks a looot of security measures. Here on CSS-Tricks.com there’s been several articles about it and version after version this was the final result:
A whole lot better in my opinion and the end-result for the user and email client is about the same
I used the code from that to build the form… So hopefully it doesn’t lack a whole lot.
Wooow, huge thanks Chris!
Thanks for shaing Chris!
Nice. Thanks. And as allways: very useable tips
off topic: Just took a look at the website of James Padolsey and i really like the scroll effect of the background. Any ide how this is done?
Greets
jQuery, thats for sure, and I think using this piece of code :)
THX. I’ll will try this…
Thanks for sharing. Very helpfull
Some of this “tricks” are quite useful, others are not…
1.a is nice, 1.b (removing the background on focus) can be done with textarea:focus {} background.image: none } no JS required ;)
2./3. HTML5 rocks :)
4. As mentioned, this should not be done…
5. Uhm… why?
6. /7./8./9. These Tricks are really useful :) Thanks for that!
@4: Many people/clients don’t like glow.
@5: Many people try removing the resize box as sometimes, resizing ruins the layout of the design. Hence, it can be quite useful too.
Oh man Chris, you can’t believe how much of a pain IE was to me with the overflow. I always used overflow:hidden and sort of hoped people won’t go back scrolling, because I really hated the automatic scrollbar that was always there even without any text. I totally overlooked the overflow:auto possibility. Thank you so much! much much pain saved!
Thanks for the useful tips !
Thx, Chris!
Great article.
Do these come with jQuery by default or is this some sort of plugin for textareas?
Great article, thanks :)
You can turn off the focus ring in Firefox by setting -moz-appearance: none, or by setting a background or border on the textarea: this will also override the native appearance.
Thank You!
cooool stuff !
Thanks for the effort :)
Great article, Chris! Informative and bookmark-worthy.
I would suggest an optimization to the elementSupportsAttribute function:
This doesn’t add any considerable performance gains, but it does demonstrate what we all love in coding with JavaScript.
Yup that is interesting !
Yeah well, I cannot see the point to all of this.
very nice… useful
Chris, can I see demo?
Sure:
https://css-tricks.com/examples/TextareaTricks/
A collection of tricks for Textarea, some i have not yet known. Thanks for posting it.
Nice article,
enjoy getting tips focused on just one element
These are the types of articles I enjoy.
Excellent Article, Added to favs, keep up the good work.
NIce tricks .. thanks for sharing Chris !
Cheers for “resize: none;” wasn’t actually aware of this :)
Instead of:
var test = document.createElement(element);
if (attribute in test) {
return true;
} else {
return false;
}
You can just do:
var test = document.createElement(element);
return (attribute in test);
Or maybe even:
return (attribute in document.createElement(element))
And finally, you put all this together, Chris!
I spent like 2-3 days trying to find the solutions for 1, 2, 4, 5, 7, 9 back in the days….
thanks for this nice tutorial :D
This is strange! I was actually looking yesterday for a guide on how to do this! Thanks Chris :D
I usually remove horizontal resize:
And I hate small textareas with only 4 rows (which many sites use for some strange reason)
Exactly what I was looking for, thx :)
This is simply retarded:
$(this)[0].value
You should use this instead:
this.value
this is a special keyword in JavaScript (as in many other programming/scripting languages) and it refers to the “owner” object of the currently running code. In this case, this refers to the textarea DOM object and value is one of its native properties.
What you did is you told jQuery to take this object ($(this)), put it in a jQuery collection, access the first element of that collection ($(this)[0]) and then access the value attribute of that object ($(this)[0].value), instead of simply accessing the attribute directly (this.value), without involving jQuery into this!
You should really learn some JavaScript and jQuery before trying to teach others anything!
And one more thing… The <code> tag is a inline tag for a reason! Wouldn’t my previous comment looked better if you’d have left the default behavior of this tag un-modified?
Pfff… Even more “awesomeness”:
var $el = $(this);
// console.log($el.text(), "value: " + $el.attr("val"));
You really chose the longest way to that element’s value attribute…
Shorter than
$el.attr(“val”)
would have been
$el.val()
or (still bad)
$el[0].value
or (the best)
this.value
…
For the helpful parts of your comment:
Awesome thanks! You’re right, I’m gonna edit the code to be more efficient like that. I actually know better, sometimes I just go fast and get it working and don’t go back and clean it up.
For the rude parts:
You should try and be less rude!
I wasnt aware of the HTML5 placeholder tag or JQuerys resize, so many thanks for highlighting those.
Yeah. Me neither. I love coming to this site because I am always learning something new.
thanks for posting the article, picked up some tips i never realized before!
Thanks Chris !!! That should be definitely bookmarked.
Nice tips…I really learn something very important thing about textarea in context of front end
If you want a more generic jQuery fallback for the HTML5 placeholder attribute, feel free to use my placeholder jQuery plugin.
Nice spam.
This post helped me a lot ,although I was aware some of the tricks mentioned above but I Placeholder tricks was the one which I found very useful as I have touched html5 yet.
Thanks for providing so nicely documented css tricks for textarea tag.
#4 on the iPhone removes the inner shadow on text boxes. Both in focus and non-focused states.
I have a question about the new “placeholder” text:
Does that text get passed in the POST/GET array if the user does not enter anything? It would really be helpful if not, otherwise it would cause extra validation when checking for blank fields that are “required” fields.
Nice post btw!
No
Hey Chris, thanks for sharing a couple of really nice tricks with us. I always wondered how to remove the resize handle on my boxes but never really looked into it… and now you have brought it to me. I think its going to be a case of experimenting with these examples and seeing how I get on. Cheers.
Agreed, this is a great tip. Those things get annoying sometimes.
Great article Chris! It’s crazy how you often manage to put up new articles just as I’m sat here scratching my head on that very subject.
On that note…does anyone know how to make the text in a textarea ‘scroll’ without scroll bars?
I have a styled form in which I have a containing my textarea which has a width and height set. The textarea is also set by cols/rows but in Firefox, when my typing reaches the bottom of the it continues down below the where you can no longer see what you are writing.
Safari automatically moves the text up so the line you are writing stays visible.
I’ve tried everything I can think of so if anyone can offer me some suggestions I’d be extremely grateful.
cheers…. man
Very Very Useful for my GUI.
Thanks 4 sharing Chris :-)
Really useful tricks – thanks for sharing;)
Its important to remember that althought you can style a text area with CSS it is always necessary to include the cols and row attribute regardless
CSS Vs cols and rows
Going into various troubles with the textarea auto resize method proposed, I found this one, which is much easier to implement and as far as I saw more cross-browser compatible : http://perplexed.co.uk/596_expanding_textarea_as_you_type.htm
The resizer js not founs,please update your link
Brilliant Brilliant Brilliant article and I learnt something new about removing the glow from active fields – it looks horrible!
One problem I’m having though is that I cannot get text to start at the top of a text-area box. I’ve tried:
vertical-align: top !important;
text-align: start;
But this has no effect.
Even tried removing ‘vertical-align: middle’ from the overall input field and changing to top but the text still appears in the middle of the area.
What am I doing wrong?
Chris –
If you use “overflow: auto;” in the textarea, it will act like “white-space: nowrap;”.
Just thought I’d share!
Any ideas anybody on my problem whereby I can’t seem to make text start at the top of a text-area box instead of in the vertical center?
There’s a couple of pretty big oversights here:
a) You’re using the jQuery data() method, but you really don’t need to. Standard use of the placeholder attribute is enough. I’ll add an example below.
b) If you change the value of the field to the placeholder text, you should change it back before submitting (or the placeholder text will get submitted for the field, which is not a good replacement for the default behavior — by default, the placeholder text is NOT submitted if the field is left blank).
I realize that the following implementation isn’t ideal — it should probably make use of an array of elements to keep the code as DRY as possible — but it’s a good start.
Then, before submitting the form, we should ideally do something like onsubmit=”return clearPlaceholders(‘#’+this.id)” in order to prevent the placeholder data from being submitted. The clearPlaceholders function looks something like this:
This is basically what I’m doing, and it’s working great.