Skip to content

Instantly share code, notes, and snippets.

@unknownuser88
Created January 6, 2014 15:49
Show Gist options
  • Save unknownuser88/8284767 to your computer and use it in GitHub Desktop.
Save unknownuser88/8284767 to your computer and use it in GitHub Desktop.
INPUT TEXT SELECTION CODE SNIPPETS
// GET CURSOR POSITION
jQuery.fn.getCursorPosition = function() {
if (this.lengh == 0) return -1;
return $(this).getSelectionStart();
}
//Set Text Selection
jQuery.fn.getSelectionStart = function() {
if (this.lengh == 0) return -1;
input = this[0];
var pos = input.value.length;
if (input.createTextRange) {
var r = document.selection.createRange().duplicate();
r.moveEnd('character', input.value.length);
if (r.text == '')
pos = input.value.length;
pos = input.value.lastIndexOf(r.text);
} else if (typeof(input.selectionStart) != "undefined")
pos = input.selectionStart;
return pos;
}
//SET CURSOR POSITION
jQuery.fn.setCursorPosition = function(pos) {
this.each(function(index, elem) {
if (elem.setSelectionRange) {
elem.setSelectionRange(pos, pos);
} else if (elem.createTextRange) {
var range = elem.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
});
return this;
};
//different version of SET CURSOR POSITION function above
function setCursorPos(node, pos) {
var node = (typeof node == "string" || node instanceof String) ? document.getElementById(node) : node;
node.focus(); //crucial for firefox
if (!node) {
return false;
} else if (node.createTextRange) {
var textRange = node.createTextRange();
textRange.collapse(true);
// textRange.moveEnd(pos); //see api textRange requires 2 params
// textRange.moveStart(pos);
textRange.moveStart('character', pos);
textRange.moveEnd('character', 0);
// console.log('textRange...');
textRange.select();
return true;
} else if (node.setSelectionRange) {
node.setSelectionRange(pos, pos);
// console.log('setSelectionRange...');
return true;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment