JSFiddle - React, Tailwind, and code Playground

by neosoyn

HTML

<p contenteditable=true data-name="title" id="hello">Hello World</p>
<p contenteditable=false data-name="title" id="hello">readonly</p>
<div id="debug"></div>

CSS

[contenteditable=true]:hover:after {
  content: ' click to edit';
  font-style: italic;
  font-size: 12px;
  font-family: sans-serif;
  color: #ccc;
  .text-stroke(0);
}

[contenteditable=true]:hover, [contenteditable]:focus {
  background: #FFFFD3;
}

[contenteditable=true]:focus {
  padding: 5px;
}

[contenteditable]:focus:after {
  content: '';
}

JavaScript

function log(s) {
    document.getElementById('debug').innerHTML = 'value changed to: ' + s;
}

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