Wednesday, June 3, 2015

HTML5 and contentEditable



HTML5 came up with contentEditable feature, its cool but difficult to work around, well is it? contentEditable is a HTML5 property and can be applied to any HTML element, thus rendering all its text editable. Lets see how to use it and bind events to it: Below is how to apply:
<li contenteditable="true" id="HTMLDivElement_lastName" href="#">Last Name</li>

Above code makes the text content under the li editable, now if you want the <li> itself to be editable(delete/edit it then the contentEditable must be applied to the <ul> that holds the li or the <div> that encapsulates the whole.) Thats pretty much on how to use.
Adding events is what is the trick for contenteditable. When i had to do this, there was not much help and few of the following observations were intresting: Why ContentEditable is Terrible However, to capture edits, jquery was a rescue, binding a combination of hover and blur did the trick. Below is javascript code:

$(this).blur(function() {
  if(before !== $(this).text()){
     $.post('./rest/htmlEditor/updateText',  $(this).attr("id") );
 }
     }); 

(this).hover(function () {
    before = $(this).text();
 , function () {
    //do nothing
 }
);

No comments:

Post a Comment