Skip to content

Commit 09027ea

Browse files
committed
Update jquery-textrange.js
General use of focus function.
1 parent 76182b6 commit 09027ea

File tree

1 file changed

+23
-15
lines changed

1 file changed

+23
-15
lines changed

jquery-textrange.js

Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,23 @@
66
* (c) 2013 Daniel Imhoff <dwieeb@gmail.com> - danielimhoff.com
77
*/
88
(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+
926
var browserType,
1027

1128
textrange = {
@@ -98,7 +115,7 @@
98115
_textrange = {
99116
xul: {
100117
get: function(property) {
101-
this[0].focus();
118+
focus(this[0]);
102119
var props = {
103120
position: this[0].selectionStart,
104121
start: this[0].selectionStart,
@@ -111,13 +128,13 @@
111128
},
112129

113130
set: function(start, end) {
114-
this[0].focus();
131+
focus(this[0]);
115132
this[0].selectionStart = start;
116133
this[0].selectionEnd = end;
117134
},
118135

119136
replace: function(text) {
120-
this[0].focus();
137+
focus(this[0]);
121138
var start = this[0].selectionStart;
122139
this.val(this.val().substring(0, this[0].selectionStart) + text + this.val().substring(this[0].selectionEnd, this.val().length));
123140
this[0].selectionStart = start;
@@ -127,10 +144,7 @@
127144

128145
msie: {
129146
get: function(property) {
130-
if (document.activeElement !== this[0]) {
131-
this[0].focus();
132-
}
133-
147+
focus(this[0]);
134148
var range = document.selection.createRange();
135149

136150
if (typeof range === 'undefined') {
@@ -159,10 +173,7 @@
159173
},
160174

161175
set: function(start, end) {
162-
if (document.activeElement !== this[0]) {
163-
this[0].focus();
164-
}
165-
176+
focus(this[0]);
166177
var range = this[0].createTextRange();
167178

168179
if (typeof range === 'undefined') {
@@ -182,10 +193,7 @@
182193
},
183194

184195
replace: function(text) {
185-
if (document.activeElement !== this[0]) {
186-
this[0].focus();
187-
}
188-
196+
focus(this[0]);
189197
document.selection.createRange().text = text;
190198
}
191199
}

0 commit comments

Comments
 (0)