Skip to content

Instantly share code, notes, and snippets.

@silviot
Created October 17, 2011 12:55
Show Gist options
  • Save silviot/1292545 to your computer and use it in GitHub Desktop.
Save silviot/1292545 to your computer and use it in GitHub Desktop.
Ext.ux.FlexTextArea: textarea field that adjusts its height to fit the text in it
// Tested with ExtJS 3.2.0
Ext.ux.FlexTextArea = Ext.extend(Ext.form.TextArea, {
maxHeight : 300, // don't grow beyond this point
minHeight : 30, // don't shrink below this height
growBy: 20, // size the textarea to leave this space blank
initComponent : function() {
Ext.ux.FlexTextArea.superclass.initComponent.call(this);
if (!this.rendered) {
this.addListener('render', this.createHelperElement, this);
} else {
this.createHelperElement();
}
this.addListener('destroy', function() {
Ext.removeNode(this.helperElement.dom);
});
},
createHelperElement: function() {
// private - create a hidden div with the same style as the textarea.
// We will use it later to calculate the height of the textarea.
this.helperElement = Ext.DomHelper.append(Ext.getBody() || document.body, {
'id': this.el.dom.id + '-preview-div'
,'tag' : 'div'
,'style' : 'position: absolute; top: -100000px; left: -100000px'
}, true);
var styles = this.el.getStyles('padding-top', 'padding-bottom', 'padding-left', 'padding-right', 'line-height', 'font-size', 'font-family', 'font-weight', 'font-style');
styles.width = this.el.getWidth() +'px' ;
this.helperElement.applyStyles(styles);
this.el.on('keyup', this.updateTextAreaHeight, this);
this.addListener('resize', function() {
this.helperElement.setStyle('width', this.el.getWidth() +'px');
this.updateTextAreaHeight();
});
this.updateTextAreaHeight();
},
updateTextAreaHeight: function() {
this.helperElement.update(
this.el.dom.value.replace(/<br \/>&nbsp;/, '<br />')
.replace(/<|>/g, ' ')
.replace(/&/g,"&amp;")
.replace(/\n/g, '<br />&nbsp;')
);
var textHeight = this.helperElement.getHeight();
var maxHeight = this.maxHeight;
var minHeight = this.minHeight;
var growBy = this.growBy;
this.el.setStyle('overflow', 'hidden');
if ( (textHeight > maxHeight ) && (maxHeight > 0) ){
textHeight = maxHeight ;
this.el.setStyle('overflow', 'auto');
}
if ( (textHeight < minHeight ) && (minHeight > 0) ) {
textHeight = minHeight ;
}
this.el.setHeight(textHeight + growBy);
}
});
Ext.reg('flextextarea', Ext.ux.FlexTextArea);
@ImpulseTheFox
Copy link

For newer ExtJS Version we can simply use this:

{
    xtype: 'textareafield',
    grow: true,
    growMax: 300
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment