jQuery Set Focus on First Character (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();
        }
    });
};

//usage
$('#elem').selectRange(3,5);
//----------------------------------------------------------------
//Other useful cursor functions:
//cursor functions
 
//set cursor position
$.fn.setCursorPosition = function(position){
    if(this.length == 0) return this;
    return $(this).setSelection(position, position);
};
 
//set selection range
$.fn.setSelection = function(selectionStart, selectionEnd) {
    if(this.length == 0) return this;
    input = this[0];
 
    if (input.createTextRange) {
        var range = input.createTextRange();
        range.collapse(true);
        range.moveEnd('character', selectionEnd);
        range.moveStart('character', selectionStart);
        range.select();
    } else if (input.setSelectionRange) {
        input.focus();
        input.setSelectionRange(selectionStart, selectionEnd);
    }
 
    return this;
};


//Set focus to beginning of input:
$.fn.focusEnd = function(){
    this.setCursorPosition(this.val().length);
};


//Set focus to end of input:
$.fn.focusStart = function(){
    this.setCursorPosition(0);
};

Leave a Reply