Saving contenteditable Content Changes as JSON with Ajax

PHOTO EMBED

Fri May 01 2020 11:41:01 GMT+0000 (Coordinated Universal Time)

Saved by @Perfect Harmony #javascript

document.addEventListener('keydown', function (event) {
  var esc = event.which == 27,
      nl = event.which == 13,
      el = event.target,
      input = el.nodeName != 'INPUT' && el.nodeName != 'TEXTAREA',
      data = {};

  if (input) {
    if (esc) {
      // restore state
      document.execCommand('undo');
      el.blur();
    } else if (nl) {
      // save
      data[el.getAttribute('data-name')] = el.innerHTML;

      // we could send an ajax request to update the field
      /*
      $.ajax({
        url: window.location.toString(),
        data: data,
        type: 'post'
      });
      */
      log(JSON.stringify(data));

      el.blur();
      event.preventDefault();
    }
  }
}, true);

function log(s) {
  document.getElementById('debug').innerHTML = 'value changed to: ' + s;
}
                                
content_copyCOPY

Elements with the contenteditable attribute can be live-edited right in the browser window. But of course those changes don’t affect the actual document on your server, so those changes don’t persist with a page refresh. One way to save the data would be to wait for the return key to be pressed, which triggers then sends the new innerHTML of the element as an Ajax call and blurs the element. Pressing escape returns the element to it’s pre-edited state.

https://css-tricks.com/snippets/javascript/saving-contenteditable-content-changes-as-json-with-ajax/