Skip to content

Instantly share code, notes, and snippets.

@jfsiii
Created September 29, 2009 20:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jfsiii/197290 to your computer and use it in GitHub Desktop.
Save jfsiii/197290 to your computer and use it in GitHub Desktop.
function cursorToPosition(el, ndx)
{
if (typeof el === 'string') { el = document.getElementById(el); } // DOM el or id
ndx = isNaN(ndx) ? el.value.length : parseInt(ndx); // end by default
if (el.setSelectionRange) {
el.focus();
el.setSelectionRange(ndx, ndx);
}
else if (el.createTextRange) {
var range = el.createTextRange();
range.collapse(true);
range.moveEnd('character', ndx);
range.moveStart('character', ndx);
range.select();
}
}
function cursorToStart(el)
{
cursorToPosition(el, 0);
}
function cursorToEnd(el)
{
cursorToPosition(el);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment