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 is a Front-end Web Developer who specialises in JavaScript & jQuery. Sam is driven and passionate about sharing his knowledge to educate others.

Free Guide:

How to Choose the Right Charting Library for Your Application

How do you make sure that the charting library you choose has everything you need? Sign up to receive this detailed guide from FusionCharts, which explores all the factors you need to consider before making the decision.

No Reader comments

Special Offer
Free course!

Git into it! Bonus course Introduction to Git is yours when you take up a free 14 day SitePoint Premium trial.