7

I have this in my body and it works

onLoad='document.forms.post.message.focus()'

but I need the cursor to be placed in the textarea at the beginning of any existing text, not at the end. This puts it at the end.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Beauford
  • 71
  • 1
  • 2
  • 2
    possible duplicate of [Howto Place cursor at beginning of textarea](http://stackoverflow.com/questions/1336585/howto-place-cursor-at-beginning-of-textarea) – Marcel Korpel Jul 28 '10 at 19:52

1 Answers1

11
function moveCaretToStart(el) {
    if (typeof el.selectionStart == "number") {
        el.selectionStart = el.selectionEnd = 0;
    } else if (typeof el.createTextRange != "undefined") {
        el.focus();
        var range = el.createTextRange();
        range.collapse(true);
        range.select();
    }
}

moveCaretToStart(document.forms["post"].elements["message"]);
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • 1
    I altered the method to take a location and created a plunker so users can try it out: https://plnkr.co/edit/YuCl18SiURfNxo3YKXAy?p=preview – raddevus Jul 12 '19 at 15:04