Reputation: 20444
The following is a simple textarea script written in jQuery that expands each textarea to fit the contents as the user is typing.
$(document).ready(function() {
$('textarea').keyup(function() {
var addin = 0;
var txtheight = $(this).scrollTop();
if(txtheight > 0){ addin = 4; }
$(this).height(($(this).height() + txtheight + addin));
});
$('textarea').keyup();
});
Problem is, if the initial content of the textarea is greater than one line, the textarea does not expand to fit the content on load as the scroll position cannot be computed.
Any ideas how to get around this.
Upvotes: 0
Views: 285
Reputation: 20444
$('textarea').each(function() {
$(this).height($(this).prop('scrollHeight'));
});
$('textarea').keyup(function() {
var addin = 0;
var txtheight = $(this).scrollTop();
if(txtheight > 0){ addin = 4; }
$(this).height(($(this).height() + txtheight + addin));
});
Correct use of 'scrollHeight'
as outlined from Danny.
Upvotes: 0
Reputation: 7518
You can try the following
$(document).ready(function() {
$('textarea').each(function() {
var addin = 0;
var txtheight = $(this).prop("scrollHeight") - $(this).height();
if(txtheight > 0){ addin = 4; }
$(this).height(($(this).height() + txtheight + addin));
});
$('textarea').keyup(function() {
var addin = 0;
var txtheight = $(this).scrollTop();
if(txtheight > 0){ addin = 4; }
$(this).height(($(this).height() + txtheight + addin));
});
$('textarea').keyup();
});
However scroll height is not supported by anything less than IE8 it looks.
Upvotes: 0
Reputation: 2377
Why don't you give this plugin a try?
http://www.jacklmoore.com/autosize
Upvotes: 1