Updated jquery selection lib

master
Jordi Boggiano 14 years ago
parent 3e98d2bfda
commit 6ee3b39484
  1. 38
      jquery.selections.js

@ -23,18 +23,7 @@
* @see $.fn.setSelection * @see $.fn.setSelection
*/ */
$.fn.setCaret = function(index) { $.fn.setCaret = function(index) {
var range, elem; this.setSelection(index, index);
elem = this.get(0);
if ($.browser.opera) {
match = this.val().match(/\n/g);
if (match) {
newlines = match.length;
index += newlines;
}
}
this.setSelection(index);
}; };
/** /**
@ -43,7 +32,7 @@
* @return int * @return int
*/ */
$.fn.getCaret = function() { $.fn.getCaret = function() {
var elem, range, elemRange, elemRangeCopy, value, caret, pos; var elem, range, elemRange, elemRangeCopy, value, caret, pos, match;
elem = this.get(0); elem = this.get(0);
value = $(elem).val(); value = $(elem).val();
@ -86,11 +75,9 @@
} }
if ($.browser.opera) { if ($.browser.opera) {
value = value.replace(/\r?\n/g, "\r\n").substr(0, caret); match = value.replace(/\r?\n/g, "\r\n").substr(0, caret).match(/\r\n/g);
match = value.match(/\r\n/g);
if (match) { if (match) {
newlines = match.length; caret -= match.length;
caret -= newlines;
} }
} }
@ -105,13 +92,24 @@
* @return object chainable * @return object chainable
*/ */
$.fn.setSelection = function(start, end) { $.fn.setSelection = function(start, end) {
var elem, range; var elem, range, match;
elem = this.get(0); elem = this.get(0);
end = end || start; end = end || start;
// standard browsers // standard browsers
if (elem.setSelectionRange) { if (elem.setSelectionRange) {
elem.focus(); elem.focus();
if ($.browser.opera) {
match = this.val().replace(/\r?\n/g, "\n").substr(0, start).match(/\n/g);
if (match) {
start += match.length;
}
match = this.val().replace(/\r?\n/g, "\n").substr(0, end).match(/\n/g);
if (match) {
end += match.length;
}
}
elem.setSelectionRange(start, end); elem.setSelectionRange(start, end);
} else if (elem.createTextRange) { } else if (elem.createTextRange) {
// old IE handling // old IE handling
@ -137,7 +135,7 @@
// standard browsers // standard browsers
if (elem.selectionStart) { if (elem.selectionStart) {
return elem.value.substr(elem.selectionStart, elem.selectionEnd); return elem.value.substring(elem.selectionStart, elem.selectionEnd);
} }
// old IE // old IE
@ -160,7 +158,7 @@
// standard browsers // standard browsers
if (elem.selectionStart) { if (elem.selectionStart) {
elem.value = elem.value.substr(0, elem.selectionStart) + text + elem.value.substr(elem.selectionEnd, elem.value.length); elem.value = elem.value.substr(0, elem.selectionStart) + text + elem.value.substr(elem.selectionEnd);
return this; return this;
} }

Loading…
Cancel
Save