Skip to content

Instantly share code, notes, and snippets.

@edvakf edvakf/autoGrow.js
Created Jan 20, 2009

Embed
What would you like to do?
//for Firefox
//javascript:
(function(){
var ta=document.createElement('textarea');
ta.rows=1;
ta.id='fuga';
ta.style.height='auto';
ta.style.minHeight='none';
document.body.appendChild(ta);
var st=getComputedStyle(ta,'');
var taLineHeight=st.height;
ta.parentNode.removeChild(ta);
javascript:
[].forEach.call(document.getElementsByTagName('textarea'),function(ta){
var pre=document.createElement('pre');
var st=getComputedStyle(ta,'');
var prop='direction fontFamily fontSize fontAdjust fontStyle fontVariant fontWeight lineHeight overflowX padding paddingBottom paddingLeft paddingTop textAlign textDirection textIndent textRendering textShadow textTransform whiteSpace width wordSpacing';
prop.split(' ').forEach(function(e){pre.style[e]=st[e]});
with(pre.style){
/*if(lineHeight=='normal')lineHeight=taLineHeight;*/
position='fixed';
maxHeight='none';
minHeight='none';
height='auto';
top=0;
left=0;
whiteSpace='pre-wrap';
visibility='hidden';
}
with(ta.style){
minHeight=st.height;
overflowY='hidden';
maxHeight='none';
height='auto';
}
document.body.appendChild(pre);
ta.addEventListener('input',function(){
pre.textContent=ta.value+'\n\n';
ta.style.height=getComputedStyle(pre,'').height;
},false);
})
})()
//for Opera
//javascript:
[].forEach.call(document.getElementsByTagName('textarea'),function(ta){
var pre=document.createElement('pre');
var st=getComputedStyle(ta,'');
var prop='direction fontFamily fontSize fontAdjust fontStyle fontVariant fontWeight lineHeight overflowX padding paddingBottom paddingLeft paddingTop textAlign textDirection textIndent textRendering textShadow textTransform whiteSpace width wordSpacing';
prop.split(' ').forEach(function(e){pre.style[e]=st[e]});
with(pre.style){
position='absolute';
maxHeight='none';
top=0;
left=0;
visibility='hidden';
}
with(ta.style){
minHeight=st.height;
overflowY='hidden';
maxHeight='none';
height='auto';
}
pre.innerHTML='<span></span>';
var span=pre.firstChild;
document.body.appendChild(pre);
ta.addEventListener('input',function(){
span.textContent=ta.value;
var texts=span.textContent.split('\n');
var mod=(texts[texts.length]=='')?0:texts.filter(function(e){return e==''}).length;
ta.rows=span.getClientRects().length+mod+1;
},false);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.