Skip to main content

Input Text Selection Code Snippets

By 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

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

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.moveEnd('character', pos);
      range.moveStart('character', pos);;
  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

        return false;
    }else if(node.createTextRange){
        var textRange = node.createTextRange();
        // textRange.moveEnd(pos); //see api textRange requires 2 params
        // textRange.moveStart(pos);
        textRange.moveStart('character', pos);
        textRange.moveEnd('character', 0);
        // console.log('textRange...');;
        return true;
    }else if(node.setSelectionRange){
        // 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.

Integromat Tower Ad