Skip to content

Instantly share code, notes, and snippets.

@daihuaye
Last active August 29, 2015 14:07
Show Gist options
  • Save daihuaye/d11ee6d4721563fc1cfb to your computer and use it in GitHub Desktop.
Save daihuaye/d11ee6d4721563fc1cfb to your computer and use it in GitHub Desktop.
Calculate the caret(cursor) position
function getCursorPosition (inp) {
if ("selectionStart" in inp) {
return inp.selectionStart
} else if (document.selection) {
inp.focus();
var sel = document.selection.createRange();
var selLen = document.selection.createRange().text.length;
sel.moveStart("character", -inp.value.length);
return sel.text.length - selLen;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment