forked from kuwabarahiroshi/jquery-autogrow-textarea
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery-autogrow-textarea.js
101 lines (80 loc) · 2.82 KB
/
jquery-autogrow-textarea.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
;(function($, doc) {
'use strict';
// Plugin interface
$.fn.autoGrowTextarea = autoGrowTextArea;
$.fn.autoGrowTextArea = autoGrowTextArea;
// Shorthand alias
if (!('autoGrow' in $.fn)) {
$.fn.autoGrow = autoGrowTextArea;
}
/**
* Initialization on each element
*/
function autoGrowTextArea() {
return this.each(init);
}
/**
* Actual initialization
*/
function init() {
var $textarea, $origin, origin, hasOffset, innerHeight, height, offset = 0;
$textarea = $(this).css({overflow: 'hidden', resize: 'none'});
if($textarea.data('autogrow-origin')){
return;
}
$origin = $textarea.clone().val('').appendTo($textarea.parent());
origin = $origin.get(0);
height = $origin.height();
origin.scrollHeight; // necessary for IE6-8. @see http://bit.ly/LRl3gf
hasOffset = (origin.scrollHeight !== height);
// `hasOffset` detects whether `.scrollHeight` includes padding.
// This behavior differs between browsers.
if (hasOffset) {
innerHeight = $origin.innerHeight();
offset = innerHeight - height;
}
$origin.hide();
$textarea
.data('autogrow-origin', $origin)
.data('autogrow-offset', offset)
.data('autogrow-initial-height', height)
.on('focus', onTextAreaFocus)
;
grow($textarea, $origin, origin, height, offset);
}
/**
* on focus
*/
function onTextAreaFocus() {
var $textarea, $origin, origin, initialHeight, offset, doGrow, timerId;
$textarea = $(this);
$origin = $textarea.data('autogrow-origin');
origin = $origin.get(0);
initialHeight = $textarea.data('autogrow-initial-height');
offset = $textarea.data('autogrow-offset');
grow.prev = $textarea.val();
doGrow = function() {
grow($textarea, $origin, origin, initialHeight, offset);
};
$textarea.on("keyup change input paste", doGrow);
$textarea.on('blur', function(){
$textarea.off("keyup change input paste", doGrow);
});
}
/**
* grow textarea height if its value changed
*/
function grow($textarea, $origin, origin, initialHeight, offset) {
var current, prev, scrollHeight, height;
current = $textarea.val();
prev = grow.prev;
if (current === prev) return;
grow.prev = current;
$origin.val(current).show();
origin.scrollHeight; // necessary for IE6-8. @see http://bit.ly/LRl3gf
scrollHeight = origin.scrollHeight;
height = scrollHeight - offset;
$origin.hide();
$textarea.height(height > initialHeight ? height : initialHeight);
}
}(jQuery, document));