-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathtextarea-autosize.js
More file actions
53 lines (40 loc) · 1.41 KB
/
textarea-autosize.js
File metadata and controls
53 lines (40 loc) · 1.41 KB
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
class TextareaAutoSize {
constructor(element) {
this.element = element;
this.verticalBorderSize = (this._styleProp("borderTopWidth") + this._styleProp("borderBottomWidth")) || 0;
this._inputHandler = this._inputHandler.bind(this);
element.addEventListener("input", this._inputHandler)
this.update()
}
_inputHandler(event) {
this.update()
}
destroy() {
this.removeEventListener("input", this._inputHandler)
this.element = null
}
update() {
// Find nearest scrollable ancestor
let box = this.element.parentElement
while (box && !/auto|scroll/.test(getComputedStyle(box).overflowY)) {
box = box.parentElement
}
const prevScroll = box?.scrollTop ?? 0
const smallestHeight = this._styleProp("fontSize")
this.element.style.height = `${smallestHeight}px`
// Firefox still triggers a vertical scrollbar but as long as we add the
// top/bottom padding to the scroll height, it's not shown. Other browsers
// do the same regardless of whether this value is added or not.
const newHeight = this.element.scrollHeight + this.verticalBorderSize
this.element.style.height = `${newHeight}px`
// Restore scroll to prevent jumping
if (box) {
box.scrollTop = prevScroll
}
}
_styleProp(name) {
const computedStyle = getComputedStyle(this.element, null)
return parseInt(computedStyle[name])
}
}
export { TextareaAutoSize }