Skip to main content

Input Text Selection Code Snippets

By Sam Deering

JavaScript

Share:

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

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

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Get practical advice to start your career in programming!


Master complex transitions, transformations and animations in CSS!