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 ?
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With