I am currently working on a script to clean up pasted text within a contenteditable div.
While the script is functioning well for most part, I have noticed that in Firefox, line breaks get removed when the text is copied within or between the divs.
Does anyone have a solution for this issue?
If I paste text from a different source, the line breaks remain intact.
I am also open to exploring alternative solutions apart from the one provided below.
// Here's a fix for pasting within contenteditable
$(document).on('paste', '[contenteditable]', function (e) {
e.preventDefault();
if (window.clipboardData) {
content = window.clipboardData.getData('Text');
if (window.getSelection) {
var selObj = window.getSelection();
var selRange = selObj.getRangeAt(0);
selRange.deleteContents();
selRange.insertNode(document.createTextNode(content));
}
} else if (e.originalEvent.clipboardData) {
content = (e.originalEvent || e).clipboardData.getData('text/plain');
document.execCommand('insertText', false, content);
}
});
div {
white-space: pre-wrap;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contenteditable="true">Copy
and
paste
this
back in the same box or the one below. Where do the line breaks go in FF?</div>
<div contenteditable="true">Copy
and
paste
this
back in the same box or the one above. Where do the line breaks go FF?</div>