forked from kuwabarahiroshi/jquery-autogrow-textarea
-
Notifications
You must be signed in to change notification settings - Fork 1
/
jquery-autogrow-textarea.js
77 lines (60 loc) · 2.1 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
;(function ($) {
'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)
.on('keyup change input paste', function () {
grow($textarea, $origin, origin, height, offset);
});
grow($textarea, $origin, origin, height, offset);
}
/**
* 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));