Skip to content

Instantly share code, notes, and snippets.

@zeshanshani
Created January 17, 2017 06:20
Show Gist options
  • Save zeshanshani/ff9c8f1bcd8bac37ba8b434ab7515ccc to your computer and use it in GitHub Desktop.
Save zeshanshani/ff9c8f1bcd8bac37ba8b434ab7515ccc to your computer and use it in GitHub Desktop.
Get the cursor position in an input field. Best to use in combination with 'keyup', 'keydown', 'focus', etc. events.
/**
* Get Cursor Position in Input Field
* @return integer Returns the cursor position.
*
* Source: Stackoverflow
* Source URI: http://stackoverflow.com/a/2897510/3107931
*
* Usage: $('input[type="text"]').getCursorPosition()
*/
$.fn.getCursorPosition = function() {
var input = this.get(0);
if (!input) return; // No (input) element found
if ('selectionStart' in input) {
// Standard-compliant browsers
return input.selectionStart;
} else if (document.selection) {
// IE
input.focus();
var sel = document.selection.createRange();
var selLen = document.selection.createRange().text.length;
sel.moveStart('character', -input.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