rss feed Twitter Page Facebook Page Github Page Stack Over Flow Page

Live edit your content without form

Would it be awesome to edit any text on a web page without entering in an edit mode (which implies also to refresh the page)?

Now it is possible, and it is actually very simple by using the HTML attribute contenteditable. This live edit concept makes all your content editable, and it is smart enough to process different type of tags as well. If you put the contenteditable on a UL you will end up creating a list whereas if you use the tag on a P you will simply edit text.

contenteditable has 3 possible values.

Browser Compatibility (source: http://caniuse.com/#feat=contenteditable)

Now, lets it make this feature more interesting. As mentioned previously, it would be great to edit the content and be able to save it to a database. Let's use this HTML document:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>editable</title>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
  <script src="/download/live-edit.js"></script>
  <style type="text/css">
  div {
   border: solid 1px #ddd;
   height: 200px;
   padding: 10px;
   width: 400px;
  }
  </style>
</head>
<body>
<h1>Live Edit</h1>

<div contenteditable="true" data-id="1">
  My Content
</div>

</body>
</html>

Now let's edit the live-edit.js. In this one, we simply have to handle how the blur event will react when the user focus out of the tag. Then call the ajax call to save the info.

$(document).ready(function() {
  $('body').on('blur',"div[contenteditable=true]",function() {
    $.ajax({
      type: 'POST',
      url: 'save.php',
      data: {
        content: $.trim($(this).text()),
        id: $(this).data('id')
      },
      success: function(msg) {
        // handle the output
      }
    });
  });
});

Now in your save.php file you simply have to save to the database.

if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
  die();
}
// sanitize the $_POST, save to the database and output a result.

There you go, you have a nice and clean solution about editing data without refreshing any contents.

Demo

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum vestibulum porttitor purus, in auctor nulla fringilla eu. Cras placerat, sem ac lobortis bibendum, magna urna aliquam orci, at sodales dui turpis sit amet velit. Nullam ut libero vitae metus tempus feugiat. Sed sagittis aliquet dolor. Pellentesque a tellus neque. Suspendisse lorem felis, ultrices vel blandit posuere, pharetra in mi. Vestibulum eget adipiscing leo. Suspendisse potenti. Aenean mi arcu, tempus nec mattis at, iaculis ac felis. Donec sem diam, aliquet ut congue quis, bibendum eget nunc. Proin pellentesque elit quis mauris placerat sed gravida risus ultricies. Donec faucibus fermentum venenatis. Nam mi nunc, luctus nec tincidunt ac, tempor eget risus.

The ajax feature has been disabled for the demo