JSFiddle - React, Tailwind, and code Playground
HTML
<script src="http://rangy.googlecode.com/svn/trunk/currentrelease/rangy-core.js"></script>
<script src="http://rangy.googlecode.com/svn/trunk/currentrelease/rangy-cssclassapplier.js"></script>
<script src="http://rangy.googlecode.com/svn/trunk/currentrelease/rangy-selectionsaverestore.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Strip editable div markup</title>
</head>
<body>
Pasting without formating. Copy some CSS above. Magic, the formating is gone after pasting!
<div id="editableDiv" contentEditable="true">Editable text</div>
<div id="cleanUp" contentEditable="true"></div>
</body>
</html>
CSS
div {
border: 1px solid;
height: 50px;
width: 200px;
}
#cleanUp {
position: absolute;
left: -10000px;
}
JavaScript
if($.browser.msie || $.browser.opera) {
var ctrl = false;
$('#editableDiv').keydown(function(e) {
if(e.which == 17 || e.which == 91) {
ctrl = true;
return false;
}
if(ctrl && e.which == 86) {
cleanUp();
} else {
ctrl = false;
}
});
$('#editableDiv').mousedown(function() {
if (e.which === 3) {
alert("Please use CRTL + V for pasting");
}
});
} else {
$(document).on('paste', '#editableDiv', function(e) {
cleanUp();
});
}
function cleanUp() {
savedSel = rangy.saveSelection();
$('#cleanUp').focus();
setTimeout(function() {
$('#editableDiv').focus();
rangy.restoreSelection(savedSel);
paste($('#cleanUp').text());
$('#cleanUp').empty()
}, 100);
}
//IE fix. IE doesn't know createContextualFragment,so we'll teach him.
if (typeof Range.prototype.createContextualFragment == "undefined") {
Range.prototype.createContextualFragment = function(html) {
var doc = this.startContainer.ownerDocument;
var container = doc.createElement("div");
container.innerHTML = html;
var frag = doc.createDocumentFragment(), n;
while ( (n = container.firstChild) ) {
frag.appendChild(n);
}
return frag;
};
}
function paste(html) {
if (window.getSelection && window.getSelection().getRangeAt) {
range = window.getSelection().getRangeAt(0);
node = range.createContextualFragment(html);
range.insertNode(node);
} else if (document.selection && document.selection.createRange) {
document.selection.createRange().pasteHTML(html);
}
}