jQuery/HTML5 Input Focus and Cursor Positions

Sam Deering

Here are some code snippets and examples of how to use jQuery & HTML5 to set cursor Input Focus and Cursor Positions which are common actions with login forms and such. Comments, improvements and suggestions welcomed.

cursor-focus

jQuery Input Focus

Simply call the focus() function to set focus to an input.

//set focus on input
$('input[name=firstName]').focus();

jsfiddle.net/z9Ldt/

HTML5 Input Focus

Awesome feature provided by HTML5… Couldn’t find this on http://html5please.com/ but I’ve tested it’s working in Chrome & Firefox but not in IE9 or below.

//AUTO INPUT FOCUS
<input type="text" name="myInput" autofocus />

jsfiddle.net/89PHL/

jQuery Set Cursor Position

jQuery function to set the cursor position to a specfic character position within an input field.

//SET CURSOR POSITION
$.fn.setCursorPosition = function(pos) {
  this.each(function(index, elem) {
    if (elem.setSelectionRange) {
      elem.setSelectionRange(pos, pos);
    } else if (elem.createTextRange) {
      var range = elem.createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
  });
  return this;
};

Example Usage

Sets cursor position after first character.

$('#username').setCursorPosition(1);

jsfiddle.net/tAZSs/

jQuery Set Cursor Position

jQuery function to auto select text (specific number of characters) within an input field.

//SELECT TEXT RANGE
$.fn.selectRange = function(start, end) {
    return this.each(function() {
        if (this.setSelectionRange) {
            this.focus();
            this.setSelectionRange(start, end);
        } else if (this.createTextRange) {
            var range = this.createTextRange();
            range.collapse(true);
            range.moveEnd('character', end);
            range.moveStart('character', start);
            range.select();
        }
    });
};

Example Usage

Selects the first 5 characters in the input.

$('#username').selectRange(0,5);

jsfiddle.net/yMUx5/

Further considerations and browsers

Attempting to set focus to a hidden element causes an error in Internet Explorer. Take care to only use .focus() on elements that are visible. To run an element’s focus event handlers without setting focus to the element, use .triggerHandler(“focus”) instead of .focus().

.

Win an Annual Membership to Learnable,

SitePoint's Learning Platform