I have a textarea with the default number of columns, like 10 or 15 or something. I want the text area to shrinkwrap the text inside on blur. Does anyone know how to do this?
So far I have
$('textarea').live('blur', function() {
var textAreaWidth = $(this).val().length;
$(this).attr('cols', 'textAreaWidth');
});
But this is ugly for obvious reasons. I just have no clue how to do this.
Any Ideas?
I have a textarea with the default number of columns, like 10 or 15 or something. I want the text area to shrinkwrap the text inside on blur. Does anyone know how to do this?
So far I have
$('textarea').live('blur', function() {
var textAreaWidth = $(this).val().length;
$(this).attr('cols', 'textAreaWidth');
});
But this is ugly for obvious reasons. I just have no clue how to do this.
Any Ideas?
Share Improve this question asked Apr 12, 2012 at 6:01 mharris7190mharris7190 1,3743 gold badges21 silver badges36 bronze badges3 Answers
Reset to default 2if you want to only decrease the size you should check that if the value is less than, say 20 and then decrease the number of columns. try this:
<textarea rows="2" cols="20"></textarea>
$('textarea').on('blur', function() {
var textAreaWidth = $(this).val().length;
if (textAreaWidth < 20) {
$(this).attr('cols', textAreaWidth);
}
$('textarea').on('keypress', function() {
$(this).attr('cols', '20');
});
});
http://jsfiddle/4bccm/
Remove the single quotes from around 'textAreaWidth' in
$(this).attr('cols', 'textAreaWidth');
This is a variable and doesn't need quotes around it.
$('textarea').bind('blur keyup', function() {
$(this).attr('cols', $(this).val().length);
});
This makes it shrink or grow as you type/blur.