Created
January 17, 2017 06:20
-
-
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.
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
/** | |
* 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