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) { //Ie and Opera don't suppor the paste event as expected. Let's catch ctrl + v. Also disable rightclick. In Opera, this just thros an alert but the context menu still appears.
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 { //If you got a normal browser, use the paste event
$(document).on('paste', '#editableDiv', function(e) {
cleanUp();
});
}
function cleanUp() {
savedSel = rangy.saveSelection(); //First, save the current cursor position
$('#cleanUp').focus(); //chagne focus to some element. Positioned out of the window. You can't focus a hidden element
setTimeout(function() {//Wait, so the pasting was made for sure into the cleanUp div.
$('#editableDiv').focus(); //focus the origin div again
rangy.restoreSelection(savedSel); //restore the cursor position which was lost when changing the focus
paste($('#cleanUp').text()); //paste the text at the current cursor position
$('#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...