1

I am making a basic online editing interface for coursework. I would like to save the content of my #textarea div every time there's a keydown event. The code works partially but I can't edit the text without the cursor going to the top of the div.

document.addEventListener('keydown', saveLocally);

const saveLocally = function() {
  let areaText = document.getElementById("textArea");
  console.log(areaText);
  let text = document.getElementById("textArea").innerHTML;
  console.log(text);
  let localData;

  localStorage.setItem('siteData', text);
  localData = localStorage.getItem('siteData');

  console.log(localData);
  console.log(localStorage.getItem('siteData'));

  areaText.innerHTML = localData;
}
<div id="inputArea">
  <div id="textArea" contenteditable="true"></div>
</div>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339

1 Answers1

1

The issue is because you immediately update the innerText of the element after someone types. This affects the cursor as the node contents are changed. You don't need to do this anyway, so the line can be removed.

You instead need to perform the logic which retrieves the value from localStorage when the page loads. Also note that you should use the keyup event instead of keydown, otherwise you'll not save the last key which was pressed. Try this:

<div id="inputArea">
  <div id="textArea" contenteditable="true"></div>
</div>
let areaText = document.getElementById("textArea");

const saveLocally = function() {
  let text = areaText.innerHTML;
  localStorage.setItem('siteData', text);
}

const retrieveSavedText = function() {
  var text = localStorage.getItem('siteData');
  areaText.innerHTML = text;
}

document.addEventListener('keyup', saveLocally);
retrieveSavedText();

Working example

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339