views:

450

answers:

3

I've found a couple resources for how to place the cursor in a textarea at the end of the text, but I can't sort out a simple way to make it appear at the beginning.

I'm prepopulating the textarea with some text and just want to make it easier on the users.

+1  A: 

The following works:

setCaretPosition("elementID", 0);

function setCaretPosition(elemId, caretPos) {
    var elem = document.getElementById(elemId);

    if(elem != null) {
        if(elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {
            if(elem.selectionStart) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else
                elem.focus();
        }
    }
}

In full disclosure, this was found on Josh Stadola's blog.

Jonathan Sampson
+2  A: 

Pass a reference to your textarea to this JS function.

function resetCursor(txtElement) { 
    if (txtElement.setSelectionRange) { 
        txtElement.focus(); 
        txtElement.setSelectionRange(0, 0); 
    } else if (txtElement.createTextRange) { 
        var range = txtElement.createTextRange();  
        range.moveStart('character', 0); 
        range.select(); 
    } 
}
Cory Larson
A: 

Google lead me to this solution pretty easily.

thorncp
Already provided as a solution.
Jonathan Sampson
Yeah, I had the page open for a few minutes without refreshing before posting. It happens.
thorncp