|
6 | 6 | * (c) 2013 Daniel Imhoff <dwieeb@gmail.com> - danielimhoff.com |
7 | 7 | */ |
8 | 8 | (function($) { |
| 9 | + |
| 10 | + /** |
| 11 | + * Sets the focus to the specified element if it isn't focused yet. |
| 12 | + * |
| 13 | + * Prevents unpleasant behaviour for textareas in IE: |
| 14 | + * If you have a textarea which is too wide to be displayed entirely and therfore has to be scrolled horizontally, |
| 15 | + * then typing one character after another will scroll the page automatically to the right at the moment you reach |
| 16 | + * the right border of the visible part. But calling the focus function causes the page to be scrolled to the left |
| 17 | + * edge of the textarea. Immediately after that jump to the left side, the content is scrolled back to the cursor |
| 18 | + * position, which leads to a flicker page every time you type a character. |
| 19 | + */ |
| 20 | + function focus(element) { |
| 21 | + if (document.activeElement !== element) { |
| 22 | + element.focus(); |
| 23 | + } |
| 24 | + } |
| 25 | + |
9 | 26 | var browserType, |
10 | 27 |
|
11 | 28 | textrange = { |
|
98 | 115 | _textrange = { |
99 | 116 | xul: { |
100 | 117 | get: function(property) { |
101 | | - this[0].focus(); |
| 118 | + focus(this[0]); |
102 | 119 | var props = { |
103 | 120 | position: this[0].selectionStart, |
104 | 121 | start: this[0].selectionStart, |
|
111 | 128 | }, |
112 | 129 |
|
113 | 130 | set: function(start, end) { |
114 | | - this[0].focus(); |
| 131 | + focus(this[0]); |
115 | 132 | this[0].selectionStart = start; |
116 | 133 | this[0].selectionEnd = end; |
117 | 134 | }, |
118 | 135 |
|
119 | 136 | replace: function(text) { |
120 | | - this[0].focus(); |
| 137 | + focus(this[0]); |
121 | 138 | var start = this[0].selectionStart; |
122 | 139 | this.val(this.val().substring(0, this[0].selectionStart) + text + this.val().substring(this[0].selectionEnd, this.val().length)); |
123 | 140 | this[0].selectionStart = start; |
|
127 | 144 |
|
128 | 145 | msie: { |
129 | 146 | get: function(property) { |
130 | | - if (document.activeElement !== this[0]) { |
131 | | - this[0].focus(); |
132 | | - } |
133 | | - |
| 147 | + focus(this[0]); |
134 | 148 | var range = document.selection.createRange(); |
135 | 149 |
|
136 | 150 | if (typeof range === 'undefined') { |
|
159 | 173 | }, |
160 | 174 |
|
161 | 175 | set: function(start, end) { |
162 | | - if (document.activeElement !== this[0]) { |
163 | | - this[0].focus(); |
164 | | - } |
165 | | - |
| 176 | + focus(this[0]); |
166 | 177 | var range = this[0].createTextRange(); |
167 | 178 |
|
168 | 179 | if (typeof range === 'undefined') { |
|
182 | 193 | }, |
183 | 194 |
|
184 | 195 | replace: function(text) { |
185 | | - if (document.activeElement !== this[0]) { |
186 | | - this[0].focus(); |
187 | | - } |
188 | | - |
| 196 | + focus(this[0]); |
189 | 197 | document.selection.createRange().text = text; |
190 | 198 | } |
191 | 199 | } |
|
0 commit comments