0

I have this code where I place the text cursor in a block of text

<h2 id="textareaEdit" contenteditable="true">
  text text text<br>text text text<br>
</h2>
<button onclick="textPlace()">focus</button>

<script>
function textPlace() {
  var el = document.getElementById("textareaEdit");
  var range = document.createRange();
  var sel = window.getSelection();
  range.setStart(el.childNodes[2], 5);
  range.collapse(true);
  sel.removeAllRanges();
  sel.addRange(range);
  el.focus();
}
</script>

I was wondering if there was a way to save the location of the text cursor when the user types and then they click off to another part of the page and then press a button to go back to the same spot.

Any ideas on how to do this? I've been trying to do this for a few days now and can't seem to get any code to save the location of the cursor

John
  • 433
  • 1
  • 5
  • 8
  • So you just want to set focus on a form element when they click a button? – mjw Jul 05 '18 at 20:14
  • Yes at a specific spot as the code currently does. But with the added extra of saving their past text cursor location. – John Jul 05 '18 at 20:16
  • 1
    this should help: https://stackoverflow.com/questions/2897155/get-cursor-position-in-characters-within-a-text-input-field/48150864#48150864 if you are navigating away from page, and returning, you could use local storage to save value. – joknawe Jul 05 '18 at 20:16
  • You basicly create a custom event handler on the textarea like `onfocusout` for example and then get the position with `selectionStart`. Save it in a variable and use it to set the position again on `focus` event. – icecub Jul 05 '18 at 20:19
  • Storage between page visits is accomplished through cookies. (document.cookie) – G Cadogan Jul 05 '18 at 20:22

0 Answers0