-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathtextarea-autogrow.js
61 lines (55 loc) · 1.96 KB
/
textarea-autogrow.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof module === 'object' && module.exports) {
module.exports = factory();
} else {
root.Autogrow = factory();
}
})(this, function(){
return function(textarea, maxLines){
var self = this;
if(maxLines === undefined){
maxLines = 999;
}
/**
* Calculates the vertical padding of the element
* @param textarea
* @returns {number}
*/
self.getOffset = function(textarea){
var style = window.getComputedStyle(textarea, null),
props = ['paddingTop', 'paddingBottom'],
offset = 0;
for(var i=0; i<props.length; i++){
offset += parseInt(style[props[i]]);
}
return offset;
};
/**
* Sets textarea height as exact height of content
* @returns {boolean}
*/
self.autogrowFn = function(){
var newHeight = 0, hasGrown = false;
if((textarea.scrollHeight - offset) > self.maxAllowedHeight){
textarea.style.overflowY = 'scroll';
newHeight = self.maxAllowedHeight;
}
else {
textarea.style.overflowY = 'hidden';
textarea.style.height = 'auto';
newHeight = textarea.scrollHeight - offset;
hasGrown = true;
}
textarea.style.height = newHeight + 'px';
return hasGrown;
};
var offset = self.getOffset(textarea);
self.rows = textarea.rows || 1;
self.lineHeight = (textarea.scrollHeight / self.rows) - (offset / self.rows);
self.maxAllowedHeight = (self.lineHeight * maxLines) - offset;
// Call autogrowFn() when textarea's value is changed
textarea.addEventListener('input', self.autogrowFn);
};
});