Wednesday, January 25, 2012

Save Changes In contenteditable As JSON With AJAX


Save Changes In contenteditable As JSON With AJAX

As you know, contents of any element in HTML5 with a contenteditable attribute can be live-edited inside the browser window. But any changes that you apply won't be saved on the actual document itself that is located in the server, so these changes won't appear anymore once you refresh the page.

You can visit the most complete resources for Web Design.
To be able to get around this and have the data saved is to wait for the Return key to be pressed, which then sends the new inner HTML of the element as an AJAX call and blurs the element. Pressing Esc returns the element to its pre-edited state.

A perfect example of this can be found on a demo created by Remy Sharp.

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

No comments:

Post a Comment