I imagined this to be straightforward, but I am unable to find anything that indicates I can use CSS to target non-empty textareas on a page.
I'm okay with JS if CSS absolutely does not support this, but even with jQuery I can't find a way to use a selector, but have to explicitly check for a .val().
Some context: I have an optional textarea that expands on focus, but if the user does decide to type something, I don't want it to shrink again when focus leaves.
$('textarea:empty')
is a nice way of doing it, but as I am dealing with textareas whose content may constantly change and be empty at one point and non-empty the next, this would still require checking every time the user focuses in and out of the textarea.I ended up adding a class
.empty
to my textarea, and checking its value every time.focusout
is fired:This way I can keep the styling in my stylesheets and the rules defined by
.empty
get used even after the user has typed something and decides to delete it all.How about using
.filter()
?Markup-wise, the
:empty
selector should allow you to select textareas that have absolutely no content, not even so much as whitespace or a line break. Conversely:not(:empty)
should let you select non-empty textareas.Selectors in CSS are mostly static though, meaning they don't account for dynamic changes such as if you edit a textarea's content after page load. Furthermore, a selector like
:empty
doesn't really account for a textarea's value so much as it checks for the presence (or absence) of content nodes in general, so I suspect it doesn't play well with forms.If you need to apply styles dynamically based on the value of a form field, you'll need to use a script to check its value using
.val()
or something similar every time it updates.Look at
:invalid & :valid
CSS3 pseudo classes:DEMO
Yes, you can do it in jQuery like:
DEMO HERE