zeshanshani
1/17/2017 - 6:20 AM

Get the cursor position in an input field. Best to use in combination with 'keyup', 'keydown', 'focus', etc. events.

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;
  }
}