Created
April 11, 2012 15:31
-
-
Save smottt/2360062 to your computer and use it in GitHub Desktop.
contenteditable example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<title>contenteditable example</title> | |
</head> | |
<body> | |
<!-- html code ... --> | |
<article contenteditable="true" date-edit-url="update.php"> | |
Some content here ... | |
</article> | |
<!-- some more html code ... --> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(function() { | |
var content_holder, content; | |
var selector = 'article[contenteditable="true"]'; | |
// prevent clicks inside editable area to fire | |
// a click event on the body | |
// and therefor saving our content before we even edit it | |
$(selector).click(function(e) { | |
e.stopPropagation(); | |
}); | |
// initialize the "save" function | |
$(selector).focus(function(e) { | |
content_holder = $(this); | |
content = content_holder.html(); | |
// one click outside the editable area saves the content | |
$('body').one('click', function(e) { | |
// but not if the content didn't change | |
if ($(e.target).is(selector) || content == content_holder.html()) { | |
return; | |
} | |
$.ajax({ | |
url: content_holder.data('edit-url'), | |
type: 'POST', | |
dataType: 'json', | |
data: { body: content_holder.html() }, | |
success: function(json) { | |
content_holder.effect('highlight', {'color': '#0f0'}, 3000); | |
}, | |
error: function() { | |
content_holder.effect('highlight', {'color': '#f00'}, 3000); | |
content_holder.html(content); | |
} | |
}); | |
}); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// note the php 5.4 short array syntax :) | |
if ($_SERVER['REQUEST_METHOD'] == 'POST') { | |
// clean any existing new line characters | |
$body = str_replace(["\n", "\r"], '', $_POST['body']); | |
// we get back actual HTML instead of new line characters | |
// so we need to replace them with new lines for proper display | |
// later on | |
$body = trim(preg_replace('~(<br\s*/?>)~im', PHP_EOL, $body)); | |
// content is ready to be updated in the database | |
// ... | |
return print json_encode(['success' => 1]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment