Input Text Selection Code Snippets

Sam Deering

Just building up a collection of input selection code snippets. The latest versions of Chrome and Firefox use the .setSelectionRange() function. Don’t forget Firefox needs focus first on an element before you can set the range. See Input.setSelectionRange.

Related post: HTML5 Input Autofocus

Get Cursor Position

// GET CURSOR POSITION
jQuery.fn.getCursorPosition = function(){
    if(this.lengh == 0) return -1;
    return $(this).getSelectionStart();
}

Set Text Selection

jQuery.fn.getSelectionStart = function(){
    if(this.lengh == 0) return -1;
    input = this[0];

    var pos = input.value.length;

    if (input.createTextRange) {
        var r = document.selection.createRange().duplicate();
        r.moveEnd('character', input.value.length);
        if (r.text == '')
        pos = input.value.length;
        pos = input.value.lastIndexOf(r.text);
    } else if(typeof(input.selectionStart)!="undefined")
    pos = input.selectionStart;

    return pos;
}

Set Cursor Position

//SET CURSOR POSITION
jQuery.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;
};

Set Cursor Position (v2)

//different version of SET CURSOR POSITION function above
function setCursorPos(node,pos){

    var node = (typeof node == "string" || node instanceof String) ? document.getElementById(node) : node;
    node.focus(); //crucial for firefox

    if(!node){
        return false;
    }else if(node.createTextRange){
        var textRange = node.createTextRange();
        textRange.collapse(true);
        // textRange.moveEnd(pos); //see api textRange requires 2 params
        // textRange.moveStart(pos);
        textRange.moveStart('character', pos);
        textRange.moveEnd('character', 0);
        // console.log('textRange...');
        textRange.select();
        return true;
    }else if(node.setSelectionRange){
        node.setSelectionRange(pos,pos);
        // console.log('setSelectionRange...');
        return true;
    }

    return false;
}

Win an Annual Membership to Learnable,

SitePoint's Learning Platform

No Reader comments

Comments on this post are closed.