Search code examples
javascriptprototypetextarea

Howto Place cursor at beginning of textarea


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.


Solution

  • 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(); 
        } 
    }