Created
January 25, 2011 01:08
-
-
Save timmywil/794334 to your computer and use it in GitHub Desktop.
Get/Set field selections
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Gets the current cursor position in a textfield | |
* to determine where to delete/update a character. | |
* @param {Element} field The raw field to get the cursor pos from. | |
* @return {Number} The index for the position of the cursor. | |
*/ | |
function getCursorPosition( field ) { | |
if ( field != null ) { | |
// IE | |
if ( document.selection ) { | |
field.focus(); | |
var sel = document.selection.createRange(); | |
sel.moveStart( 'character', -field.value.length ); | |
return sel.text.length; | |
} | |
// Others | |
else if ( field.selectionStart || field.selectionStart == '0' ) { | |
return field.selectionStart; | |
} | |
} | |
// Something went wrong. | |
return -1; | |
} | |
/** | |
* Sets the cursor position to a previous state | |
* if the field was updated somewhere in the middle. | |
* @param {Element} field The raw field. | |
* @param {Number} pos The position to set to. | |
*/ | |
function setCursorPosition( field, pos ) { | |
if ( field != null ) { | |
// IE | |
if ( field.createTextRange ) { | |
var range = field.createTextRange(); | |
range.move('character', pos); | |
range.select(); | |
} | |
// Others | |
else if ( field.selectionStart ) { | |
field.focus(); | |
field.setSelectionRange( pos, pos ); | |
} | |
// Something's wrong. Just focus on it. | |
else | |
field.focus(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment