Skip to content

Commit 35c44c5

Browse files
Mottiealalonde
authored andcommitted
Calculate scrollbar width & use when overflowing. Fixes component#21
1 parent d369de0 commit 35c44c5

File tree

1 file changed

+25
-6
lines changed

1 file changed

+25
-6
lines changed

index.js

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,8 @@
99
var properties = [
1010
'direction', // RTL support
1111
'boxSizing',
12-
'width', // on Chrome and IE, exclude the scrollbar, so the mirror div wraps exactly as the textarea does
1312
'height',
1413
'overflowX',
15-
'overflowY', // copy the scrollbar for IE
1614

1715
<<<<<<< HEAD
1816
'borderTopWidth',
@@ -56,6 +54,25 @@ var properties = [
5654

5755
var isBrowser = (typeof window !== 'undefined');
5856
var isFirefox = (isBrowser && window.mozInnerScreenX != null);
57+
var scrollbarWidth = 0;
58+
59+
// modified from http://davidwalsh.name/detect-scrollbar-width
60+
function getScrollbarWidth() {
61+
if (!scrollbarWidth) {
62+
var div = document.createElement('div'),
63+
style = div.style;
64+
document.body.appendChild(div);
65+
style.position = 'absolute';
66+
style.top = '-9999px';
67+
style.left = 0;
68+
style.width = style.height = '100px';
69+
style.overflow = 'scroll';
70+
style.visibility = 'hidden';
71+
scrollbarWidth = div.offsetWidth - div.clientWidth;
72+
document.body.removeChild(div);
73+
}
74+
return scrollbarWidth;
75+
};
5976

6077
function getCaretCoordinates(element, position, options) {
6178
if (!isBrowser) {
@@ -97,14 +114,16 @@ function getCaretCoordinates(element, position, options) {
97114
}
98115
});
99116

117+
style.overflowY = element.scrollHeight > parseInt(computed.height) ? 'scroll' : 'auto';
118+
100119
if (isFirefox) {
101120
// Firefox lies about the overflow property for textareas: https://bugzilla.mozilla.org/show_bug.cgi?id=984275
102-
if (element.scrollHeight > parseInt(computed.height))
103-
style.overflowY = 'scroll';
121+
// so we still use computed width
122+
style.width = computed.width;
104123
} else {
105-
style.overflow = 'hidden'; // for Chrome to not render a scrollbar; IE keeps overflowY = 'scroll'
124+
// include scrollbar width - Chrome & IE renders scrollbar and gets width added
125+
style.width = parseInt( computed.width, 10 ) + getScrollbarWidth() + 'px';
106126
}
107-
108127
div.textContent = element.value.substring(0, position);
109128
// The second special handling for input type="text" vs textarea:
110129
// spaces need to be replaced with non-breaking spaces - http://stackoverflow.com/a/13402035/1269037

0 commit comments

Comments
 (0)