Use Ajax to Save Changes in Contenteditable as JSON

Contents of any HTML5 element 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.

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. you can then press Esc to return the element to its pre-edited state.

You can see more of this in Remy Sharp’s demo .

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

 

 

Incoming search terms for the article:

Related Posts

Correctly Embed Watermarks In Portrait And Landscape Photos Using Conditional Actions In Photoshop CS6.1

Oregon-Inspired Photoshop Tutorial

Create Google Play’s Tab Navigation Using jQuery And CSS

PS Advanced Compositioning