Created
October 17, 2011 12:55
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 \/> /, '<br />') | |
.replace(/<|>/g, ' ') | |
.replace(/&/g,"&") | |
.replace(/\n/g, '<br /> ') | |
); | |
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For newer ExtJS Version we can simply use this: