Similar to the below JSFiddle (which I bookmarked and do not know from where the original question emerged):
http://jsfiddle.net/mJMpw/6/
<input type="text" value="" placeholder="Autosize" data-autosize-input='{ "space": 10 }' />
input {
width: 200px;
min-width: 200px;
max-width: 300px;
transition: width 0.25s;
}
Is there a way to fix the width of a text field to, for example 200px only, and have the height of the text field grow if a user adds more text than the 200px is able to contain? I would like more rows to be added, if a user needs more room to type... so I need the height, not the width, to resize dynamically.
Thanks!
As others explained, input field can't have multiline text, you should use textarea to mimic an input field, and jQuery to make it auto resize vertically (with fixed width).
JS:
//This span is used to measure the size of the textarea
//it should have the same font and text with the textarea and should be hidden
var span = $('<span>').css('display','inline-block')
.css('word-break','break-all')
.appendTo('body').css('visibility','hidden');
function initSpan(textarea){
span.text(textarea.text())
.width(textarea.width())
.css('font',textarea.css('font'));
}
$('textarea').on({
input: function(){
var text = $(this).val();
span.text(text);
$(this).height(text ? span.height() : '1.1em');
},
focus: function(){
initSpan($(this));
},
keypress: function(e){
//cancel the Enter keystroke, otherwise a new line will be created
//This ensures the correct behavior when user types Enter
//into an input field
if(e.which == 13) e.preventDefault();
}
});
CSS:
textarea {
width:200px;
resize:none;
overflow:hidden;
font-size:18px;
height:1.1em;
padding:2px;
}
This new updated demo has some bugs fixed and it also supports Enter key, max-height limit, the width does not need to be set fixedly at first (instead we can set its min-width). It's much more full-featured.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With