Created
March 9, 2011 09:51
-
-
Save jeremi/861962 to your computer and use it in GitHub Desktop.
inspired from the jquery.autogrow-textarea.js plugin
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
AS.AutoResizeTextAreaView = SC.TextFieldView.extend( | |
/** @scope AS.AutoResizeTextAreaView.prototype */ { | |
isTextArea: YES, | |
layout: {minHeight: 50}, | |
didCreateLayer: function() { | |
sc_super(); | |
this.initAutoResize(); | |
}, | |
willDestroyLayer: function() { | |
sc_super(); | |
this.$input().unbind(); | |
}, | |
mouseWheel: function() { | |
//If the textarea is in the scrollView, we let the scrollView handle this event | |
return NO; | |
}, | |
_shadow: null, | |
initAutoResize: function() { | |
var self = this, $this = this.$input(), | |
shadow = $('<div></div>').css({ | |
position: 'absolute', | |
top: -10000, | |
left: -10000, | |
width: this.get("layout").width, | |
fontSize: $this.css('fontSize'), | |
fontFamily: $this.css('fontFamily'), | |
lineHeight: $this.css('lineHeight'), | |
resize: 'none' | |
}).insertAfter($this), | |
callback = function(evt) { | |
SC.RunLoop.begin(); | |
self._valueChanged(evt); | |
SC.RunLoop.end(); | |
}; | |
$this.change(callback).keyup(callback).keydown(callback); | |
this._shadow = shadow; | |
this.invokeLater(this._valueChanged); | |
}, | |
_valueChanged: function() { | |
var shadow = this._shadow, height, layout = this.get("layout"), minHeight = layout.minHeight || 50, | |
times = function(string, number) { | |
for (var i = 0, r = ''; i < number; i ++) r += string; | |
return r; | |
}, | |
val = this.$input().val().replace(/</g, '<') | |
.replace(/>/g, '>') | |
.replace(/&/g, '&') | |
.replace(/\n$/, '<br/> ') | |
.replace(/\n/g, '<br/>') | |
.replace(/ {2,}/g, function(space) { return times(' ', space.length -1) + ' ' }); | |
shadow.html(val); | |
height = Math.max(shadow.height() + 20, minHeight); | |
if (layout.height !== height) { | |
this.$input().css('height', height); | |
this.$().css('height', height); | |
this.adjust("height", height); | |
} | |
}.observes("value") | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment