JSFiddle - React, Tailwind, and code Playground
by bodine30
HTML
<div>
<h1 class="InlineTextEditor editable ">
<div tabIndex="-1">
<p contenteditable="true" spellcheck="false" title="asdfa" tabIndex="-1">
This element is editable and should only allow pasting of dataType 'text/plain'
</p>
</div>
</h1>
<div>
<br>
<p contenteditable="true">This element is editable and should allow different dataTypes (e.g. 'text/html', or 'text/plain') to be pasted within</p>
CSS
h1 [contenteditable] {
cursor: text;
padding: 2px;
border: 1px solid transparent;
text-align: left;
background:#eef;
color:crimson;
font:bold 30px/1.5em Verdana;
text-shadow:2px 2px 0px rgba(100,0,150,.5);
}
h1 [contenteditable]:focus {
background: white;
border: 1px solid black;
white-space: normal;
text-overflow: clip;
}
h1 > div {display:inline-block;}
JavaScript
var editableParent = document.querySelector(".InlineTextEditor > div"),
obsConfig = {
childList: true, subtree: true
},
handleChildListChanged = function handleChildListChanged(arr, inst) {//debugger;
var item = arr[0].target,
parent = (
(
item.hasAttribute("contenteditable") ||
item.parentNode === editableParent
) ?
item.parentNode :
item),
editable = parent.querySelector("[contenteditable]"),
text = parent.get('text');
editable.innerHTML = text;
parent.innerHTML = editable.outerHTML;
if(typeof observer.disconnect !== "undefined") {observer.disconnect();}
_onFocus(inst);
},
observer = new (window.MutationObserver ||
window.WebKitMutationObserver ||
window.MSMutationObserver ||
function(fn){return fn;}
)(handleChildListChanged);
function handleBeforePaste(e) {
console.log("handleBeforePaste");
var editableElement = editableParent.querySelector("[contenteditable]");
if('dataset' in editableParent) {
editableParent.dataset.cachedText = escape($(editableElement).get('text').trim());
} else {
editableParent.setAttribute("data-cached-text",escape($(editableElement).get('text').trim()));
}
}
function onPaste(e) {
setTimeout(function(){observer([{target:editableParent}]);},10);
}
function _onFocus(e) {
debugger;
console.log(typeof e);
var ed = editableParent.querySelector("[contenteditable]"),sel,range;
ed.focus();
//if(e.event){return;}
if(!e.event && window.getSelection && document.createRange) {
//debugger;
range = document.createRange();
range.selectNodeContents(ed.lastChild);
sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
...