edit in place  [ 733 views ]

Goal: To create a simple editable field on my page

There is a simple way to create an editable DIV field. We can start the editing by click or simple on getting focus. So in this case the editor is the container itself. Forget to create input boxes or textarea-s and forget the additional event handlings.

  <div class="t" spellcheck="false" contenteditable="true" maxlength="40"></div>

spellcheck=”false” – use this because of firefox spell check feature!

In this sample we have a DIV container with editable content. In this case we need

  1. to catch the focus event (start the editing)
  2. watch the keydown
  3. check the max length if applied
  4. manage the editing end events (save -> ENTER or skip, restore -> ESC)


.off('focus').on('focus', function(e) {
$(this).data('x', $(this).html()); // store the original content in data

$(this).on('keydown', function(e) {
var dd = false,
ml = $(this).attr('maxlength'), // max length watching
keycode = e.keyCode;

if (keycode === 27) { // escape key -> end of editing (no save!)
dd = true;
}
else if (keycode === 13) { // enter key -> end of editing with save
// ... save here ...
dd = true;
$(this).data('x', $(this).html());
}
else {
var printable =
(keycode > 47 && keycode < 58) || // number keys keycode == 32 || keycode == 13 || // spacebar & return key(s) (if you want to allow carriage returns) (keycode > 64 && keycode < 91) || // letter keys (keycode > 95 && keycode < 112) || // numpad keys (keycode > 185 && keycode < 193) || // ;=,-./` (in order) (keycode > 218 && keycode < 223); // [\]' (in order) if (printable) { return $(this).text().length <= ml; } } if (dd) { // end editing $(this).off('keydown'); e.target.blur(); return false; } }); return false; }) .off('blur').on('blur', function() { // after end editing $(this).html($(this).data('x')); }); [/js] One more thing. We can set the :focus style to detect the editing mode like this: [css] .t:focus { outline:1px dotted #f00; color: #f00; } [/css]

#sidebar a { color:#fff; } #sidebar ul ul li { color: #DEF585; } #sidebar h2 { color: #fff; } #sidebar ul p, #sidebar ul select { color: #BEDDBE; } #backfly { background: url(images/golfBallWallPaper.jpg) left bottom fixed repeat-x #65a51d; }