Code Snippet

Home » Code Snippets » JavaScript » Saving contenteditable Content Changes as JSON with Ajax

Saving contenteditable Content Changes as JSON with Ajax

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.

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;
}

Live demo on JS Bin by Remy Sharp.

Subscribe to The Thread

  1. I don’t get how to save this to the server? I tried just removing the comment signs to make the ajax work, but no luck. Anyone?

  2. Alok Saldanha

    What if the user pressed undo(ctrl-z or apple-z)? Then the contenteditable element is restored to its former state, but the reversion is not persisted to the database. Is there a cross-platform way to detect this?

  3. Saša

    in order to make it work with FF too

    document.execCommand('undo', false, null); // restore to previus state

  4. How will I save the output to cookie so if I refresh and or close page the content will still be there.

    Thanks

    Dan

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~