Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can keep the cursor in its position in textarea after auto-submitting?

I have a form and textarea, I do auto submit for form after x seconds ... But every time auto submit is done the cursor jumps out of textarea ... so how can I keep the cursor after submitting in old position in texrarea ?

like image 755
code Avatar asked Sep 14 '25 00:09

code


1 Answers

In your auto submit code get the current position of the cursor in the textarea. You can do it with this function (where id is the id attribute of the textarea element):

function getCaretPosition(id) {
    var txt = document.getElementById(id);
    var startPos = txt.selectionStart;
    var endPos = txt.selectionEnd;
    return endPos;
}

Than store the the value somewhere (in localstorage for instance), and after the form submit restore the cursor position with this function:

function setCaretPosition(id) {
    var txt = document.getElementById(id);
    if(txt.createTextRange) {
      var range = txt.createTextRange();
      range.collapse(true);
      range.moveEnd('character', caretPos);
      range.moveStart('character', caretPos);
      range.select();
      return;
    }

    if(txt.selectionStart) {
      txt.focus();
      txt.setSelectionRange(caretPos, caretPos);
    }
}

where the caretPos is the cursor position stored before the submit. Here is simple demo to see how the functions work https://jsfiddle.net/p0oc8tjs/2/

like image 89
xxxmatko Avatar answered Sep 15 '25 15:09

xxxmatko