Reputation: 300
I currently have a content editable div which I use as an editor but I'm looking to strip html (not including <br>
tags) on paste.
At the moment I have another div <div class="hiddendiv common editor"></div>
this one which collects all text and data added to the contenteditable
div in order to determine height of the contenteditable div.
I've become confused and unsure how I will do this.
My Question is: How do I strip html formatting (not including <br>
tags) whilst inserting text at the cursor caret on paste with jQuery?
HTML:
<div contenteditable='true' id="textarea" class="editor plain-box large-box textarea text common text-content-input quicksand color-dark-grey" data-text="Start typing..."></div>
<div class="hiddendiv common editor"></div>
jQuery
function pasteHtmlAtCaret(html) {
var sel, range;
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
var el = document.createElement("div");
el.innerHTML = html;
var frag = document.createDocumentFragment(), node, lastNode;
while ((node = el.firstChild)) {
lastNode = frag.appendChild(node);
}
range.insertNode(frag);
if (lastNode) {
range = range.cloneRange();
range.setStartAfter(lastNode);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
} else if (document.selection && document.selection.type != "Control") {
document.selection.createRange().pasteHTML(html);
}
}
$('#textarea').on("paste", function() {
var textarea = $('#textarea').html();
var hidden_div = $('.hiddendiv').html(textarea);
var plain_text = hidden_div.text();
$('#textarea').pasteHtmlAtCaret(plain_text);
});
var txt = $('#textarea'),
hiddenDiv = $(document.createElement('div')),
content = null;
txt.addClass('txtstuff');
hiddenDiv.addClass('hiddendiv common editor');
$('body').append(hiddenDiv);
txt.on('keyup input propertychange', function () {
content = $(this).html();
content = content.replace(/\n/g, '<br>');
hiddenDiv.html(content + '<br>');
$(this).css('height', hiddenDiv.height());
});
Upvotes: 6
Views: 1839
Reputation: 1506
This may be what you’re looking for:
<div contenteditable="plaintext-only" id="textarea" data-text="Start typing..."></div>
Upvotes: 0